count()
¶
count
()
¶
Returns an integer representing the number of objects in the database matchingthe QuerySet
. The count()
method never raises exceptions.
Example:
# Returns the total number of entries in the database.
Entry.objects.count()
# Returns the number of entries whose headline contains 'Lennon'
Entry.objects.filter(headline__contains='Lennon').count()
A count()
call performs a SELECT COUNT(*)
behind the scenes, so youshould always use count()
rather than loading all of the record into Pythonobjects and calling len()
on the result (unless you need to load theobjects into memory anyway, in which case len()
will be faster).
Note that if you want the number of items in a QuerySet
and are alsoretrieving model instances from it (for example, by iterating over it), it’sprobably more efficient to use len(queryset)
which won’t cause an extradatabase query like count()
would.