简体   繁体   English

从 Django values() 获取外键值

[英]Getting foreign key values from Django values()

I am getting data objects from Django models using我正在使用 Django 模型获取数据对象

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:您可以像这样在.values()使用查找:

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.这就是为什么使用的原因之一.values() [Django的DOC]是不是一个好主意:它侵蚀模型的逻辑层。

You can use .annotate(…) [Django-doc] to add the name to the values:您可以使用.annotate(…) [Django-doc]将名称添加到值中:

from django.db.models import F

tabledata = Entity.objects.filter(quarter=1).annotate(
    creator_name=F('creator__name')
).values()

Then it will appear under the 'creator_name' key in the dictionary.然后它将出现在字典中的'creator_name'键下。

But using .values() is often only useful in specific usecases.但是使用.values()通常只在特定用例中有用。 For example a GROUP BY on a specific value, or in a subquery.例如对特定值或在子查询中的GROUP BY You should make use of serializers if you want to make JSON for a given model.如果您想为给定模型制作 JSON,您应该使用序列化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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