[Django]-Select a COUNT using Django model?

47👍

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.

54👍

Use count():

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

0👍

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/

Leave a comment