About Counting Occurrences

You can count the occurrences of a certain string in all records of a model using annotations like this:

1
2
3
4
5
6
7
from django.db.models import Count
from places.models import Place

for record in Place.objects.values("city").annotate(
    occurrences=Count("city"),
).order_by("-occurrences"):
    print(f"{record['city']}: {record['occurrences']}")

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