Skip to content

Commit

Permalink
Raise an error when an aggregation references another aggregation of …
Browse files Browse the repository at this point in the history
…the same call
  • Loading branch information
David-Wobrock committed Sep 27, 2020
1 parent 91669cc commit cb177f9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
9 changes: 8 additions & 1 deletion django/db/models/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,15 @@ def aggregate(self, *args, **kwargs):
query = self.query.chain()
for (alias, aggregate_expr) in kwargs.items():
query.add_annotation(aggregate_expr, alias, is_summary=True)
if not query.annotations[alias].contains_aggregate:
annotation = query.annotations[alias]
if not annotation.contains_aggregate:
raise TypeError("%s is not an aggregate expression" % alias)
for expr in annotation.get_source_expressions():
if expr.contains_aggregate and hasattr(expr, 'refs') and expr.refs in kwargs:
name = expr.refs
raise exceptions.FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (
annotation.name, name, name))

return query.get_aggregation(self.db, kwargs)

def count(self):
Expand Down
5 changes: 5 additions & 0 deletions tests/aggregation/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,11 @@ def test_annotate_over_annotate(self):

self.assertEqual(author.sum_age, other_author.sum_age)

def test_aggregate_referencing_aggregate(self):
msg = "Cannot compute Avg('age'): 'age' is an aggregate"
with self.assertRaisesMessage(FieldError, msg):
Author.objects.annotate(age_alias=F('age')).aggregate(age=Sum(F('age_alias')), avg_age=Avg(F('age')))

def test_annotated_aggregate_over_annotated_aggregate(self):
with self.assertRaisesMessage(FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate"):
Book.objects.annotate(Max('id')).annotate(Sum('id__max'))
Expand Down

0 comments on commit cb177f9

Please sign in to comment.