← Django Foundations
12 / 25
Lesson 12 — Aggregations per group
Totals per group
Sometimes you need a total for each user, not one grand total. Django does this with .values("user").annotate(total=Sum("amt")). In Python, a defaultdict(int) is handy: it is a dict where a missing key starts at 0, so you can add to it straight away.
totals = defaultdict(int)
totals["Sam"] += 50 # no KeyError
Note: the exercise runs in your browser without Django installed, so it is a small plain-Python simulation of what Django does for you.
Why it matters: "sales per product" or "posts per author" are grouped totals — reports are full of them.
Want it another way?
Task
Fill the loop so totals holds the sum of amounts per user, then print each user and total.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.