Django Django

What's the difference between `annotate()` and `aggregate()`?

Dima Ноя 15, 2026

Short Answer

aggregate() ends the queryset and hands back a plain dict summarising the whole set; annotate() returns a queryset with one extra value attached to every row. That is the entire distinction — one produces a report line, the other produces a column. Because annotate() keeps a queryset, its results are still model instances you can filter, order, and slice, and filtering on the annotated value becomes a HAVING clause rather than a WHERE. The trap to know about: two aggregates over two different relations in one annotate() multiply each other, and the fix is distinct=True.


How It Works

aggregate() is terminal. It compiles the queryset's filters into a SELECT containing only the aggregate functions, runs it immediately, and returns a dict keyed by the names you gave. There is no GROUP BY, because there is nothing to group by — the whole result set is one group. Nothing chains off it; you have left the queryset world and are holding data.

annotate() is not terminal. It adds an expression to the SELECT list and returns a new queryset, so each row that comes back is still a model instance with one extra attribute on it. When the expression is an aggregate over a related table, Django adds a LEFT OUTER JOIN to reach that table and a GROUP BY on the model's own columns, so the aggregate is computed per parent row rather than across everything. The join is a left join deliberately: a shipment with no scans must still appear, with a count of zero.

Because the annotated value is part of the query, it can be used by the rest of the query. filter(scan_count__gte=2) cannot become a WHERE, since the count does not exist until rows are grouped — so Django emits HAVING instead. Ordering on an annotation works the same way, which is what makes "top ten by related count" a single query.

The multiplication problem follows directly from the joins. Annotating two related counts adds two left joins to one query, and the database produces one row per combination — a shipment with two scans and three charges yields six rows, and both counts then see six. Nothing is wrong with the SQL; it is counting exactly what it was asked to count. Count("scans", distinct=True) tells it to count distinct scan ids within each group, which recovers the intended numbers.

That failure hides in small data. A shipment with one scan and one charge produces one row and two counts of one, which is correct. The bug only appears when a parent has more than one of both, which is why it so often survives development and shows up on real data.


Seeing It Run

These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:

python3 main.py

aggregate() ends the queryset

Two shipments, summarised over their own column.

# depot/models.py
from django.db import models


class Shipment(models.Model):
    reference = models.CharField(max_length=20)
    weight_kg = models.IntegerField()


class Scan(models.Model):
    shipment = models.ForeignKey(Shipment, related_name="scans", on_delete=models.CASCADE)
    dock = models.CharField(max_length=20)


class Charge(models.Model):
    shipment = models.ForeignKey(Shipment, related_name="charges", on_delete=models.CASCADE)
    amount = models.IntegerField()


# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=["depot"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    DEFAULT_AUTO_FIELD="django.db.models.AutoField",
    USE_TZ=False,
)
django.setup()

from django.db import connection

from depot.models import Charge, Scan, Shipment


def seed():
    with connection.schema_editor() as editor:
        editor.create_model(Shipment)
        editor.create_model(Scan)
        editor.create_model(Charge)
    first = Shipment.objects.create(reference="SHP-4471", weight_kg=120)
    second = Shipment.objects.create(reference="SHP-4408", weight_kg=340)
    for dock in ("dock-7", "dock-9"):
        Scan.objects.create(shipment=first, dock=dock)
    Scan.objects.create(shipment=second, dock="dock-7")
    for amount in (40, 25, 15):
        Charge.objects.create(shipment=first, amount=amount)
    Charge.objects.create(shipment=second, amount=90)
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, connection, seed
from django.db.models import Avg, Sum

seed()

totals = Shipment.objects.aggregate(total_kg=Sum("weight_kg"), average_kg=Avg("weight_kg"))
print("aggregate() returns:", type(totals).__name__)
print("               value:", totals)
print("SQL:", connection.queries[-1]["sql"])


aggregate() returns: dict
               value: {'total_kg': 460, 'average_kg': 230.0}
SQL: SELECT SUM("depot_shipment"."weight_kg") AS "total_kg", AVG("depot_shipment"."weight_kg") AS "average_kg" FROM "depot_shipment"


A dict, not a queryset — the call ran immediately and there is nothing left to chain. The SQL selects the two aggregate functions and nothing else, with no GROUP BY, because the whole table is a single group. The keys are the names given as keyword arguments; omit them and Django generates names like weight_kg__sum. This is the shape you want for one summary line, and the wrong shape for anything per-row.

Try it: Put a filter in front of the aggregation: Shipment.objects.filter(weight_kg__gt=200).aggregate(...). Before you run it, decide what the dictionary will hold and where the filter will show up in the SQL. The result is {'total_kg': 340, 'average_kg': 340.0} and the statement ends with WHERE "depot_shipment"."weight_kg" > 200: aggregate() summarises exactly the rows the queryset would have returned, so whatever you chain before it narrows the set, not the result.


annotate() adds a value to every row

Replace main.py. Counting scans per shipment, which crosses a relation.

# main.py
from bootstrap import Shipment, connection, seed
from django.db.models import Count

seed()

annotated = Shipment.objects.annotate(scan_count=Count("scans")).order_by("reference")
print("annotate() returns:", type(annotated).__name__)
for shipment in annotated:
    print(f"  {type(shipment).__name__} {shipment.reference} weight={shipment.weight_kg} scans={shipment.scan_count}")
print("SQL:", connection.queries[-1]["sql"])

busy = list(annotated.filter(scan_count__gte=2).values_list("reference", flat=True))
print("filtered on the annotation:", busy)
print("which became:", "HAVING" + connection.queries[-1]["sql"].split("HAVING", 1)[1].split("ORDER BY")[0].rstrip())


annotate() returns: QuerySet
  Shipment SHP-4408 weight=340 scans=1
  Shipment SHP-4471 weight=120 scans=2
SQL: SELECT "depot_shipment"."id", "depot_shipment"."reference", "depot_shipment"."weight_kg", COUNT("depot_scan"."id") AS "scan_count" FROM "depot_shipment" LEFT OUTER JOIN "depot_scan" ON ("depot_shipment"."id" = "depot_scan"."shipment_id") GROUP BY "depot_shipment"."id", "depot_shipment"."reference", "depot_shipment"."weight_kg" ORDER BY "depot_shipment"."reference" ASC
filtered on the annotation: ['SHP-4471']
which became: HAVING COUNT("depot_scan"."id") >= 2


Each row is still a Shipment — the model's own fields are there and scan_count rides alongside as an ordinary attribute. The SQL shows how: a left join to reach the scans, and a GROUP BY on the shipment's columns so the count is per shipment rather than overall. And because the queryset survived, filter(scan_count__gte=2) chains onto it, compiling to HAVING rather than WHERE — a count cannot be tested before the rows are grouped.

Try it: Change scan_count__gte=2 to scan_count__gte=1 and predict both closing lines. The list becomes ['SHP-4408', 'SHP-4471'] and the clause becomes HAVING COUNT("depot_scan"."id") >= 1. Only the number in HAVING moved; the GROUP BY and the JOIN stayed the same, because a filter on an annotation applies to the groups once they are formed, not to the rows they are formed from.


Two related counts in one call multiply

Replace main.py. SHP-4471 has two scans and three charges; ask for both counts together.

# main.py
from bootstrap import Shipment, seed
from django.db.models import Count

seed()

print("actual data: SHP-4471 has 2 scans and 3 charges; SHP-4408 has 1 and 1")

both = Shipment.objects.annotate(
    scans_n=Count("scans"),
    charges_n=Count("charges"),
).order_by("reference")
for shipment in both:
    print(f"  plain Count    {shipment.reference}: scans={shipment.scans_n} charges={shipment.charges_n}")

fixed = Shipment.objects.annotate(
    scans_n=Count("scans", distinct=True),
    charges_n=Count("charges", distinct=True),
).order_by("reference")
for shipment in fixed:
    print(f"  distinct=True  {shipment.reference}: scans={shipment.scans_n} charges={shipment.charges_n}")


actual data: SHP-4471 has 2 scans and 3 charges; SHP-4408 has 1 and 1
  plain Count    SHP-4408: scans=1 charges=1
  plain Count    SHP-4471: scans=6 charges=6
  distinct=True  SHP-4408: scans=1 charges=1
  distinct=True  SHP-4471: scans=2 charges=3


Two and three became six and six. The second left join pairs every scan with every charge, so the group for SHP-4471 holds 2 × 3 = 6 rows and both counts report the row total rather than the thing they name. distinct=True counts distinct ids within the group and restores 2 and 3. Look at SHP-4408: one scan and one charge give 1 × 1 = 1, so its numbers are right either way — which is exactly why this survives a test fixture with one of everything and breaks on production data. Sums are worse still, because Sum(..., distinct=True) is not a general fix; separate queries or Subquery are.


Edge Cases and Gotchas

  • Order matters around filter(). filter(...).annotate(...) narrows rows before aggregating; annotate(...).filter(...) aggregates first and filters on the result with HAVING. Both are valid and they answer different questions.
  • A left join means zero, not missing. A shipment with no scans is still returned with scan_count of 0, which is usually wanted — but Avg and Sum over no rows give None, not 0, so use Coalesce when a number is required.
  • aggregate() after a slice summarises the slice. Django wraps the limited query in a subquery, so queryset[:10].aggregate(Sum(...)) totals those ten rows rather than the whole table — convenient when intended, misleading when the slice was only there for display.
  • Naming an annotation after an existing field is an error. annotate(weight_kg=...) raises ValueError, since the attribute would collide with the model field on every returned instance.
  • values() before annotate() changes the grouping. In that position the named fields become the GROUP BY key and you get one row per distinct combination instead of one per model row.

Summary

aggregate() collapses a queryset to a single dict of totals and ends the chain; annotate() attaches a computed value to each row and keeps the queryset, so the annotation can be filtered and ordered on. Aggregates over relations add joins, and two of them in one call inflate each other.

  • aggregate() runs immediately and returns a dict; there is no GROUP BY because the whole set is one group.
  • annotate() returns model instances carrying an extra attribute, adding a LEFT OUTER JOIN and a GROUP BY when the aggregate crosses a relation.
  • Filtering on an annotated value compiles to HAVING, because the value does not exist until rows are grouped.
  • Two aggregates over two relations in one annotate() produce a row per combination, so both counts return the product; distinct=True fixes counts.
  • That inflation is invisible when each parent has at most one related row on each side, which is why fixtures rarely catch it.

Чтобы получить доступ к облачной лаборатории, необходимо войти в систему.

Войти