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.
- [Django]-Filter Queryset on empty ImageField
- [Django]-How do I remove Label text in Django generated form?
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
16👍
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 }}
- [Django]-Django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
- [Django]-How to define two fields "unique" as couple
- [Django]-Where's my JSON data in my incoming Django request?
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.
- [Django]-Django Model Field Default Based Off Another Field in Same Model
- [Django]-Accessing dictionary by key in Django template
- [Django]-How do I send empty response in Django without templates