← All notes

Summarize a Django QuerySet with aggregate() or annotate()

Answer: Django has two common ways to run aggregate queries. aggregate() generates summary values over an entire QuerySet. annotate() attaches a summary to each object, such as a Count of related books on each publisher.

aggregate() and annotate()

Appending an aggregate() clause onto the QuerySet calculates a value such as Avg("price") over the set. all() is redundant in that example. annotate(num_books=Count("book")) is the per-object form. Avg, Max, Min, and Count appear in the examples.

What the database computes

The aggregate functions shown below are available by default in SQLite. The result of avg() is NULL if there are no non-NULL inputs. Avg("price", default=0) is one of the examples. For aggregate functions like max() and count(), the input order does not matter. count(*) with no arguments returns the total number of rows in the group. sum() returns NULL for no non-NULL input rows, but total() returns 0.0.

| aggregate() | annotate() | |---|---| | aggregate() | Summary values over an entire QuerySet | | annotate() | Per-object summary such as Count | | Avg | avg(); NULL if there are no non-NULL inputs | | Count | count() over a group of rows |

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Django docs, Aggregation; SQLite, Built-in Aggregate Functions. BSD-3-Clause; Public-Domain. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Django docs, Aggregation; SQLite, Built-in Aggregate Functions. BSD-3-Clause; Public-Domain.

Cite this

Permanent ID: iil:note:77xwhzn4

iinventedlight. 2026. "Summarize a Django QuerySet with aggregate() or annotate()." iinventedlight Library, iil:note:77xwhzn4, version of 2026-11-19. https://iinventedlight.com/library/notes/django-aggregation/. License: CC-BY-4.0.

@misc{iil_note_77xwhzn4,
  author = {{iinventedlight}},
  title = {{Summarize a Django QuerySet with aggregate() or annotate()}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-19},
  url = {https://iinventedlight.com/library/notes/django-aggregation/},
  note = {Permanent ID iil:note:77xwhzn4. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/django-aggregation.md.