Django check: Use .count() instead of len()

A count() call is more efficient if you just want to number of objects in the database matching the QuerySet.


According to the Django documentation, a queryset.count() is more efficient than len(queryset) in returning the number of objects in a database matching the QuerySet.

Do: queryset.count() - this will perform single SELECT COUNT(*) some_table query, all computation is carried on RDBMS side, Python just needs to retrieve the result number with fixed cost of O(1).

Don't: len(queryset) - this will perform SELECT * FROM some_table query, fetching whole table O(N) and requiring additional O(N) memory for storing it.


  1. Django documentation
  2. Stackoverflow discussion