sedavidw
sedavidw

Reputation: 11691

Use values() in Django query to get Model instead of ID

I have the following setup in Django

class Class1(Model):

    search_field = IntegerField()
    field2 = ForeignKey(Class2)

class Class2(Model):

    field3 = ForeignKey(Class3)

class Class3(Model):

    #lots of useful stuff...

I am doing a query in Class1 with the intention of getting back an instance of Class3, however Class1 and Class2 have a lot of information that I don't want to load, so I want to use values (or something that lets me do this more efficiently). I do something like

q = Class1.objects.filter(search_field=search_criteria).values('field2__field3').latest()

But when this comes back I get a dictionary that looks like:

{'field2__field3': ID}

Where ID is a key to an instance of Class3. Is there a way to get the instance of the class directly from values (or some other query utility)?

Upvotes: 3

Views: 2212

Answers (2)

user9876
user9876

Reputation: 11102

Rewrite your code to:

q = Class3.objects.filter(class2__class1__search_field=search_criteria)

I.e. directly ask for the objects you really want, and use the reverse relationships from Class3 back to Class2 and Class1 as part of your filter criteria.

It may help to set related_name or related_query_name on the ForeignKeys that you are using - if set, these are the names to use in the filter() arguments. If not set, they default to the class name.

Upvotes: 4

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48932

A simple rule with Django queries is to always query on the thing you want to get back. So if you want a Class3, start your query with that.

Class3.objects.filter(class2__class1__search_field=search_criterion).latest()

Upvotes: 5

Related Questions