Andrew
Andrew

Reputation: 443

Select a COUNT using Django model?

Does anyone know if there's a way to just select the number of rows matching a query in Django? I have a search I've written that splits results into sets of 40, but I'd like to display the total number of results as well. I could to something like len(Model.objects.filter(name__icontains=search)), but it seems like that would be grossly inefficient (since I'm assuming that would generate a "SELECT * FROM model" and then all of the resulting objects). Any suggestions?

Upvotes: 34

Views: 94131

Answers (3)

MD. SHIFULLAH
MD. SHIFULLAH

Reputation: 1731

For all row count of a table/model:

pattern:

Model.objects.count()

example:

User.objects.count()

For specific row count of a table/model:

pattern:

Model.objects.filter(user__id=1).count()

example:

User.objects.filter(user__id=1).count()

For further info please visit: https://docs.djangoproject.com/en/4.1/topics/db/aggregation/

Upvotes: 0

Seth
Seth

Reputation: 46423

Use count():

>>> Model.objects.count()
42
>>> Model.related_set.count()
102
>>> Model.related_set.filter(blah=42).count()
3

Upvotes: 56

Matthew Rankin
Matthew Rankin

Reputation: 461157

There are two main ways to handle this:

  1. Use Django's count() QuerySet method — simply append count() to the end of the appropriate QuerySet
  2. Generate an aggregate over the QuerySet — Aggregation is when you "retrieve values that are derived by summarizing or aggregating a collection of objects." Ref: Django Aggregation Documentation

The links above are to the applicable sections of Django's documentation.

Upvotes: 48

Related Questions