Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the following, I tried to take into account all your constraints: filtering on fields of List, on fields of Item, counting items , and grouping by list.</p> <p>The solution I see is that you could use values() (here is the django doc about this : <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values</a>)</p> <pre><code>from django.db.models import Count lists = list(List.objects.filter(user=user)) items=Item.objects.values(list).filter(archived=False,list__in=lists).annotate(count=Count("id")) #you will get a list of dicts of the form [{'count':2,'list':5},...] where 5 is the id of the list #now, you can match you list with you item counts in python list_items_count_dict={} for item in items: list_items_count_dict[item['list']]=item['count'] for list in lists : list.item_count = list_items_count_dict.get(list.id) </code></pre> <p>That will make only 2 queries, one for getting the lists, the other for computing the item counts. Afterwards, you will have two loops (that could probably be replaced by list comprehension one-liners ), but only for the lists you are interested in.</p> <p>afterwards, in your template, you can use </p> <pre><code>{{list.item_count}} </code></pre> <p>There might be a more elegant option, but that is what I have found right now. I am also certain that you could reduce the number of query to one by using custom sql.</p> <p>Disclaimer: I have not tested this code, but I have tested similar code on similar models. You could have problems because <code>list</code> is one of the keyword of the Python language.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload