views:

185

answers:

2

I'm trying to filter a table in django based on the value of a particular field of a foreign key.

For example I have two models - Project and Asset, Project has a "name" field and each asset has a ForiegnKey(Project) field. I'd like to filter my asset list based on the name of the associated project.

Currently I am performing two queries...

project_list = Project.objects.filter(name__contains="Foo")         
asset_list = Asset.objects.filter( desc__contains=filter, project__in=project_list).order_by('desc')

but i'm wondering if there is a way to specify this kind of filtering in the main query?

+1  A: 

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

Michael Greene
Is this going to hit the DB twice, should I be using select_related() to make this more optimal?
Fraser Graham
You can add a .query.as_sql() to see what sql will actually be executed.
fastmultiplication
+1  A: 

Asset.objects.filter( project__name__contains="Foo" )

Fragsworth
Thanks,I had tried that but apparently I had forgotten to use double underscore.
Fraser Graham