From a934d377af2f90329485917fead8723f45d7a56e Mon Sep 17 00:00:00 2001 From: Hannes Ljungberg Date: Wed, 3 Nov 2021 15:34:37 +0100 Subject: [PATCH] Fixed #33262 -- Fixed crash of conditional aggregation on Exists(). --- django/contrib/postgres/aggregates/mixins.py | 2 +- django/db/models/aggregates.py | 2 +- tests/aggregation/test_filter_argument.py | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/django/contrib/postgres/aggregates/mixins.py b/django/contrib/postgres/aggregates/mixins.py index f2ba5c4439..0796abb830 100644 --- a/django/contrib/postgres/aggregates/mixins.py +++ b/django/contrib/postgres/aggregates/mixins.py @@ -30,7 +30,7 @@ class OrderableAggMixin: sql, sql_params = super().as_sql(compiler, connection, ordering=( 'ORDER BY ' + ', '.join(ordering_expr_sql) )) - return sql, sql_params + ordering_params + return sql, (*sql_params, *ordering_params) return super().as_sql(compiler, connection, ordering='') def set_source_expressions(self, exprs): diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index 596a161669..8c4eae7906 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -87,7 +87,7 @@ class Aggregate(Func): compiler, connection, template=template, filter=filter_sql, **extra_context ) - return sql, params + filter_params + 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 650cb8e460..32494cc84f 100644 --- a/tests/aggregation/test_filter_argument.py +++ b/tests/aggregation/test_filter_argument.py @@ -141,3 +141,11 @@ class FilteredAggregateTests(TestCase): ) ) self.assertEqual(aggregate, {'max_rating': 4.5}) + + def test_filtered_aggregate_on_exists(self): + aggregate = Book.objects.values('publisher').aggregate( + max_rating=Max('rating', filter=Exists( + Book.authors.through.objects.filter(book=OuterRef('pk')), + )), + ) + self.assertEqual(aggregate, {'max_rating': 4.5})