About Counting Related Objects

You can count the related objects of a category using annotations like this:

1
2
3
4
5
6
7
from django.db.models import Count
from categories.models import Category

for category in Category.objects.annotate(
    place_count=Count("place"),
).order_by("-place_count"):
    print(f"{category.title}: {category.place_count}")

Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL