← Back to Django, page 2

django-0021 · Medium mid

What is the difference between annotate() and aggregate() in the Django ORM?

aggregate() reduces the whole QuerySet to a single dict of values, such as the overall average mark. annotate() adds a computed value to each row, which becomes a GROUP BY when the expression uses an aggregate, such as the average mark per class. values() before annotate() picks the grouping columns.

Full answer

Both use aggregate functions such as Count, Sum, Avg, Max and Min, but they return different shapes.

aggregate() is terminal. It runs right away and returns a dict:

python
Mark.objects.aggregate(avg=Avg("score"), top=Max("score"))
# {'avg': 71.0, 'top': 90}

annotate() returns a QuerySet where each object gets a new attribute:

python
ClassRoom.objects.annotate(students_count=Count("students"))

SQL: SELECT ..., COUNT(student.id) FROM classroom LEFT JOIN student ... GROUP BY classroom.id.

Grouping by a column instead of by object uses values() first:

python
Mark.objects.values("subject").annotate(avg=Avg("score"))

Useful details:

  • Filter on the annotation with filter() after annotate (becomes HAVING): .annotate(n=Count("students")).filter(n__gte=2).
  • Conditional aggregation: Count("marks", filter=Q(marks__score__gte=75)).
  • Two Count annotations over different multi-valued relations multiply rows through the JOINs and give inflated numbers. Use distinct=True or subqueries.
  • Avg returns a float; Sum of an empty set returns None. Since Django 4.0, pass default=0 to get 0 instead.
  • Default ordering in Meta.ordering used to sneak into GROUP BY; since Django 3.1 it is ignored in these queries, but explicit order_by() fields still affect grouping.

Rule of thumb: one number for the whole set is aggregate; one number per row or group is annotate.

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, Max, Q, Sum

print(Mark.objects.aggregate(avg=Avg("score"), top=Max("score")))
print(Mark.objects.filter(score__gt=1000).aggregate(total=Sum("score", default=0)))

for room in ClassRoom.objects.annotate(
    students_count=Count("students", distinct=True),
    good=Count("students__marks", filter=Q(students__marks__score__gte=75)),
).order_by("name"):
    print(room.name, room.students_count, room.good)

per_subject = Mark.objects.values("subject").annotate(avg=Avg("score")).order_by("subject")
print(list(per_subject))

busy = ClassRoom.objects.annotate(n=Count("students")).filter(n__gte=2).values_list("name", flat=True)
print(list(busy))

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): {'avg': 71.0, 'top': 90} {'total': 0} 10A 2 0 10B 2 3 [{'subject': 'Maths', 'avg': 75.0}, {'subject': 'Science', 'avg': 67.0}] ['10A', '10B']

Key points

  • aggregate() returns a dict for the whole set
  • annotate() adds a value per row or group
  • values() before annotate() sets GROUP BY columns
  • Filter after annotate becomes HAVING
  • Multiple multi-valued Counts can inflate results

Common mistakes

  • Using annotate when you want one number, then looping to sum in Python
  • Counting across two multi-valued relations without distinct=True
  • Expecting Sum over no rows to be 0 without default=0
  • Forgetting values() and grouping by every model field

Follow-ups

  • How would you get the top scorer in each class in one query?
  • What is the difference between filter() before and after annotate()?
  • When would you use Subquery and OuterRef instead?

Tips

  • Give the output shape of each in one sentence
  • Show values().annotate() for GROUP BY
  • Mention the inflated count trap with multiple joins