Django: optimizing queries
Posted
by
Josh
on Stack Overflow
See other posts from Stack Overflow
or by Josh
Published on 2010-12-31T04:33:14Z
Indexed on
2010/12/31
7:54 UTC
Read the original article
Hit count: 152
django
I want to list the number of items for each list. How can I find this number in a single query, rather than a query for each list?
Here is a simplified version of my current template code:
{% for list in lists %}
<li>
{{ listname }}:
{% with list.num_items as item_count %}
{{ item_count }} item{{ item_count|pluralize }}
{% endwith %}
</li>
{% endfor %}
lists is passed as: List.objects.filter(user=user)
and num_items is a property of the List model:
def _get_num_items(self):
return self.item_set.filter(archived=False).count()
num_items = property(_get_num_items)
This queries SELECT COUNT(*) FROM "my_app_item" WHERE...
n times, where n is the number of lists. Is it possible to make a single query here?
© Stack Overflow or respective owner