The choice between len() and count() depends on the situation, and you should deeply understand how they work in order to use them correctly.
Let me introduce you a few scenarios:
(most important) If you want to know only the number of elements and do not plan to handle them in any way, it is extremely important to use count() :
DO: queryset.count() - this will execute one SELECT COUNT(*) some_table , all calculations are performed on the DBMS side, Python just needs to get the result number with a fixed cost O (1)
DON'T: len(queryset) - this will execute a SELECT * FROM some_table , retrieving the entire O (N) table and requiring additional O (N) memory to store it. This is the worst thing you can do.
When you intend to extract a set of queries in any case, it is better to use len() which will not cause an additional query to the database, since count() will be:
len(queryset)
Amount:
queryset.count()
The second case returned (when a set of requests has already been received):
for obj in queryset:
Everything will be clear as soon as you look "under the hood":
class QuerySet(object): def __init__(self, model=None, query=None, using=None, hints=None):
Good links in Django docs:
Krzysiek Oct 07 '17 at 11:02 2017-10-07 11:02
source share