multiplied_aggregates
Scan a Django project for annotations where multi-valued joins multiply rows, causing Count and Sum aggregates to return inflated values. Identifies these incorrect queries for correction.
Instructions
Aggregates whose numbers are wrong because a join multiplied the rows.
Order.objects.annotate(lines=Count("lines"), shipments=Count("shipments"))
Joining two multi-valued relations gives the cartesian product of them: an
order with 3 lines and 2 shipments produces 6 rows, and both counts come
back as 6. Nothing raises. Two plausible numbers, both the product of the
two, usually on a dashboard nobody can check by hand.
Only Count and Sum are reported. A join repeats rows uniformly within each
group, so Min and Max return the value they would anyway and Avg divides a
multiplied total by a multiplied count - including them reported a correct
query as a defect on the first real project this saw.
Count(distinct=True) is treated as correct. Sum has no equivalent and needs
a Subquery, so a query is still reported when every Count in it is distinct
but a Sum crosses a second relation.
Django's own documentation warns about this and no linter checks it.
Args:
search_path: directory to scan. Defaults to the configured project.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| search_path | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||