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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…