Count vs len on a Django QuerySet

antonagestam picture antonagestam · Jan 14, 2013 · Viewed 66.2k times · Source

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.)

Answer

Andy Hayden picture Andy Hayden · Jan 14, 2013

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's SELECT COUNT(*), and Django provides a count() 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.