Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

django - Select a single field from a foreign key

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

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]

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...

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?

Note, I'm trying really hard here to avoid making a raw query

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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 }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...