Skip to content

Commit

Permalink
Refs #27849 -- Fixed filtered aggregates crash on filters that match …
Browse files Browse the repository at this point in the history
…everything.
  • Loading branch information
charettes authored and felixxm committed Nov 7, 2022
1 parent 77cf70e commit 967f875
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
23 changes: 12 additions & 11 deletions django/db/models/aggregates.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,18 @@ def as_sql(self, compiler, connection, **extra_context):
if self.filter:
if connection.features.supports_aggregate_filter_clause:
filter_sql, filter_params = self.filter.as_sql(compiler, connection)
template = self.filter_template % extra_context.get(
"template", self.template
)
sql, params = super().as_sql(
compiler,
connection,
template=template,
filter=filter_sql,
**extra_context,
)
return sql, (*params, *filter_params)
if filter_sql:
template = self.filter_template % extra_context.get(
"template", self.template
)
sql, params = super().as_sql(
compiler,
connection,
template=template,
filter=filter_sql,
**extra_context,
)
return sql, (*params, *filter_params)
else:
copy = self.copy()
copy.filter = None
Expand Down
13 changes: 13 additions & 0 deletions tests/aggregation/test_filter_argument.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,16 @@ def test_filtered_aggregate_empty_condition(self):
max_rating=Max("rating", filter=Q(rating__in=[]))
)
self.assertEqual(aggregate, {"max_rating": None})

def test_filtered_aggregate_full_condition(self):
book = Book.objects.annotate(
authors_count=Count(
"authors",
filter=~Q(authors__in=[]),
),
).get(pk=self.b1.pk)
self.assertEqual(book.authors_count, 2)
aggregate = Book.objects.aggregate(
max_rating=Max("rating", filter=~Q(rating__in=[]))
)
self.assertEqual(aggregate, {"max_rating": 4.5})

0 comments on commit 967f875

Please sign in to comment.