← Back to Django, page 4

django-0068 · Medium mid

How do you compute several grouped statistics in one Django query using Count, Sum and Avg with the filter argument and values().annotate()?

Call values("field") to choose the GROUP BY column, then annotate() with aggregate functions. Each aggregate accepts filter=Q(...) to count or sum only matching rows, which turns several separate queries into one SQL statement with FILTER or CASE WHEN. Order matters: filters before values() restrict rows, filters after annotate() act like HAVING.

Full answer

Question to answer: for each subject, what is the average score and how many students scored 70 or more? A loop with several queries is slow; one grouped query is better.

python
Mark.objects.values("subject").annotate(
    avg=Avg("score"),
    high=Count("id", filter=Q(score__gte=70)),
    total=Sum("score"),
).order_by("subject")

How it works:

  • values("subject") before annotate() sets the GROUP BY. After annotate(), values() just selects columns.
  • filter=Q(...) is conditional aggregation. SQLite and PostgreSQL emit FILTER (WHERE ...), other backends use CASE WHEN.
  • aggregate(...) (not annotate) collapses the whole queryset into one dict, for example the overall average.
  • Without values(), annotate() groups by each row's primary key, giving per-object statistics such as Student.objects.annotate(total=Sum("marks__score")).

The order of filter() and annotate() changes results:

  • filter(...).annotate(Count("marks")) filters rows first, then counts only the matching marks.
  • annotate(Count("marks")).filter(marks__count__gt=1) becomes HAVING, filtering groups after counting.

Pitfalls: combining two multi-valued annotations (Count("marks") and Count("courses")) joins both tables, which multiplies rows and inflates counts; use distinct=True or Subquery. Default ordering from Meta.ordering used to alter GROUP BY, so call order_by() explicitly. Use Coalesce(Sum(...), 0) when empty groups should be 0 rather than None.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.test.utils import CaptureQueriesContext


class ClassRoom(models.Model):
    name = models.CharField(max_length=10)
    class Meta:
        app_label = "school"


class Student(models.Model):
    name = models.CharField(max_length=40)
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (ClassRoom, Student, Mark):
        editor.create_model(m)

a, b = ClassRoom.objects.create(name="10A"), ClassRoom.objects.create(name="10B")
for i, (name, room) in enumerate([("Asha", a), ("Ravi", a), ("Kiran", b), ("Meera", b)]):
    s = Student.objects.create(name=name, class_room=room)
    Mark.objects.create(student=s, subject="Maths", score=60 + i * 10)
    Mark.objects.create(student=s, subject="Science", score=55 + i * 8)

from django.db.models import Avg, Count, Q, Sum
from django.db.models.functions import Coalesce

stats = Mark.objects.values("subject").annotate(
    avg=Avg("score"), high=Count("id", filter=Q(score__gte=70)), total=Sum("score")
).order_by("subject")
for row in stats:
    print(row)

print(Mark.objects.aggregate(overall=Avg("score"), best=Sum("score", filter=Q(subject="Maths"))))

per_student = Student.objects.annotate(total=Sum("marks__score")).order_by("-total")
print([(s.name, s.total) for s in per_student])

# filter before annotate restricts the rows counted; filter after becomes HAVING
before = ClassRoom.objects.filter(students__marks__score__gte=80).annotate(n=Count("students__marks")).order_by("name")
after = ClassRoom.objects.annotate(n=Count("students__marks")).filter(n__gte=4).order_by("name")
print([(c.name, c.n) for c in before], [(c.name, c.n) for c in after])
print(Student.objects.filter(name="Nobody").aggregate(total=Coalesce(Sum("marks__score"), 0)))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'subject': 'Maths', 'avg': 75.0, 'high': 3, 'total': 300} {'subject': 'Science', 'avg': 67.0, 'high': 2, 'total': 268} {'overall': 71.0, 'best': 300} [('Meera', 169), ('Kiran', 151), ('Ravi', 133), ('Asha', 115)] [('10B', 2)] [('10A', 4), ('10B', 4)] {'total': 0}

Key points

  • values() before annotate() defines GROUP BY
  • filter= on an aggregate gives conditional counts in one query
  • aggregate() returns one dict; annotate() adds per-row or per-group values
  • Order of filter() and annotate() changes the meaning
  • Two multi-valued annotations inflate counts; use distinct=True

Common mistakes

  • Running one query per group instead of values().annotate()
  • Forgetting order_by() and getting unexpected grouping
  • Combining two multi-valued Count annotations without distinct=True
  • Forgetting Coalesce so empty sums are None

Follow-ups

  • How would you compute a percentage of total per group?
  • What SQL does filter= generate on PostgreSQL versus MySQL?
  • How do you avoid inflated counts when joining two relations?

Tips

  • Show the values-then-annotate order
  • Explain the HAVING behaviour
  • Mention distinct=True