In Django, given that I have a QuerySet
that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs)
or qs.count()
?
(Also given that counting the objects in the same iteration is not an option.)
Although the Django docs recommend using count
rather than len
:
Note: Don't use
len()
on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL'sSELECT COUNT(*)
, and Django provides acount()
method for precisely this reason.
Since you are iterating this QuerySet anyway, the result will be cached (unless you are using iterator
), and so it will be preferable to use len
, since this avoids hitting the database again, and also the possibly of retrieving a different number of results!).
If you are using iterator
, then I would suggest including a counting variable as you iterate through (rather than using count) for the same reasons.