简体   繁体   中英

Getting foreign key values from Django values()

I am getting data objects from Django models using

tabledata=Entity.objects.filter(quarter=1)

Using this method, I am able to extract the values of the objects specified by the foreign key like so

tabledata[0].creator.name

However when I changed the code to

tabledata=Entity.objects.filter(quarter=1).values()

I can extract only foreign key values but not the values of the object data linked with the foreign key. Something like

tabledata[0][creator][name]  does not work

Is there a way to extract the values this way?

You can use lookup in .values() like this:

entities = Entity.objects.filter(quarter=1).values('creator__name')
print(entities[0]['creator__name'])

You can fetch other fields too if you need:

Entity.objects.filter(quarter=1).values('creator__name', 'direct_field', 'another_direct_field')

This is one of the many reasons why using .values() [Django-doc] is not a good idea: it erodes the logical layer of the model.

You can use .annotate(…) [Django-doc] to add the name to the values:

from django.db.models import F

tabledata = Entity.objects.filter(quarter=1).annotate(
    
).values()

Then it will appear under the 'creator_name' key in the dictionary.

But using .values() is often only useful in specific usecases. For example a GROUP BY on a specific value, or in a subquery. You should make use of serializers if you want to make JSON for a given model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM