从外键中选择一个字段 [英] Select a single field from a foreign key

查看:118
本文介绍了从外键中选择一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个很简单(简化)的模型

So I have a a very simple (simplified) model

class MyObject(models.Model):
    owning_user = models.ForeignKey(User, null=True)

现在我正在尝试一个我的模板在这些对象的列表中迭代,以确定是否应该显示类似于

Now in one of my templates I'm trying to iterate over a list of these objects to determine whether something should be displayed similar to this

{% for my_object in foo.my_object_set %}
    {% if my_object.owning_user.id == user.id %}
         Show Me!
    {% endif %}

这工作正常,但是我发现是查询

This works fine, but what I am finding is that the query

my_object.owning_user.id

返回所有用户的每个字段,然后再获取在django调试工具栏中进行验证的id,并检查连接查询

returns every field from the owning user before getting the id which is verified both in django debug tool bar, and checking the connection queries

# django-debug-toolbar states this is repeated multiple times     
SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = 1

# The following test code also confirms this
from django.db import connection
conn = connection
bearing_type.owning_user.id
print conn.queries[-1]

现在,由于此查询重复超过1000次,每次查询需要2ms,因此只需执行2秒即可所有我关心的是id ...

Now since this query repeats over 1000 times and takes 2ms per query it is taking 2 seconds just to perform this - when all I care about is the id...

无论如何,我只需执行一个查询,只需从 owning_user instea

Is there anyway at all that I can just perform a query to get just the id from the owning_user instead of having to query all the fields?

请注意,我正在努力尝试避免进行原始查询

推荐答案

如果您使用 my_object.owning_user_id 而不是 my_object。 owning_user ,那么Django将使用id而不是查找用户。

If you use my_object.owning_user_id instead of my_object.owning_user, then Django will use the id instead of looking up the user.

在这种情况下,你只需要id,但如果你需要其他用户属性,您可以使用 select_related 。在视图中,您可以:

In this case, you only need the id, but if you needed other user attributes, you could use select_related. In the view, you would do:

foo.my_object_set.select_related('user')

在模板中,您没有太多的控制权,因为您无法传递参数。

In the template, you don't have as much control, since you can't pass arguments.

{{ foo.my_object_set.select_related }}

这篇关于从外键中选择一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆