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?
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.
{{ some_queryset.count }}
in the template, will issue another DB call. if this is a value you'll display more than once, store the value in the view and pass it to the template.
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.
Just to highlight @Yuji'Tomita'Tomita comment above as a separate answer:
There is a filter called
length
to calllen()
on anything.
So you could use:
{{ some_queryset|length }}
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.
length
to call len() on anything.{{ any_iterable|length }}
some_queryset.all|length
? Is this optimum in terms of the SQL generated? Thesome_queryset.count
usesSELECT COUNT(*)
... instead of selecting all the model fields. I don't know how significant this is in terms of performance, I guess for something with a large query_set this could be significant?