[Django]-Django – show the length of a queryset in a template

102👍

Give {{ some_queryset.count }} a try.

This is better than using len (which could be invoked with {{ some_queryset.__len__ }}) because it optimizes the SQL generated in the background to only retrieve the number of records instead of the records themselves.

34👍

some_queryset.count() or {{some_queryset.count}} in your template.

dont use len, it is much less efficient. The database should be doing that work. See the documentation about count().

However, taking buffer’s advice into account, if you are planning to iterate over the records anyway, you might as well use len which will involve resolving the queryset and making the resulting rows resident in main memory – this wont go to waste because you will visit these rows anyway. It might actually be faster, depending on db connection latency, but you should always measure.

16👍

Just to highlight @Yuji’Tomita’Tomita comment above as a separate answer:

There is a filter called length to call len() on anything.

So you could use:

{{ some_queryset|length }}

15👍

The accepted answer is not entirely correct. Whether you should use len() (or the length-filter in a template) vs count() depends on your use case.

If the QuerySet only exists to count the amount of rows, use count().

If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.

From the docs:

Note that if you want the number of items in a QuerySet and are also retrieving model instances from it (for example, by iterating over it), it’s probably more efficient to use len(queryset) which won’t cause an extra database query like count() would.

Although it seems that with related objects that you have already eager-loaded using prefetch_related(), you can safely use count() and Django will be smart enough to use the cached data instead of doing another SELECT-query.

Leave a comment