diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index ec21e5fd11..ab38a33bf0 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -105,17 +105,18 @@ class Aggregate(Func): 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 diff --git a/tests/aggregation/test_filter_argument.py b/tests/aggregation/test_filter_argument.py index caf2cd3d6f..3ef0401d4d 100644 --- a/tests/aggregation/test_filter_argument.py +++ b/tests/aggregation/test_filter_argument.py @@ -205,3 +205,16 @@ class FilteredAggregateTests(TestCase): 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})