django - show the length of a queryset in a template

Django

Django Problem Overview


In my html file, how can I output the size of the queryset that I am using (for my debugging purposes)

I've tried

{{ len(some_queryset) }}

but that didn't work. What is the format?

Django Solutions


Solution 1 - Django

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.

Solution 2 - Django

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.

Solution 3 - Django

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

Solution 4 - Django

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbharalView Question on Stackoverflow
Solution 1 - DjangoEvan GrimView Answer on Stackoverflow
Solution 2 - DjangoPreet KukretiView Answer on Stackoverflow
Solution 3 - DjangoAlejandroVDView Answer on Stackoverflow
Solution 4 - DjangoAndreas BergströmView Answer on Stackoverflow