From 53269bcaaf1fc2ce4db797d7d8935d98a53494df Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Thu, 6 Dec 2018 10:40:49 -0500 Subject: [PATCH] Fixed #30011 -- Fixed queries that reuse filtered aggregates. Thanks Taqi Abbas and Raphael Kimmig for the report. --- django/db/models/aggregates.py | 2 +- tests/aggregation/test_filter_argument.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index cc4b0c52a6..b270640ea5 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -27,7 +27,7 @@ class Aggregate(Func): def get_source_expressions(self): source_expressions = super().get_source_expressions() if self.filter: - source_expressions += [self.filter] + return source_expressions + [self.filter] return source_expressions def set_source_expressions(self, exprs): diff --git a/tests/aggregation/test_filter_argument.py b/tests/aggregation/test_filter_argument.py index 54836178c4..63dee59464 100644 --- a/tests/aggregation/test_filter_argument.py +++ b/tests/aggregation/test_filter_argument.py @@ -79,3 +79,11 @@ class FilteredAggregateTests(TestCase): msg = 'Star cannot be used with filter. Please specify a field.' with self.assertRaisesMessage(ValueError, msg): Count('*', filter=Q(age=40)) + + def test_filtered_reused_subquery(self): + qs = Author.objects.annotate( + older_friends_count=Count('friends', filter=Q(friends__age__gt=F('age'))), + ).filter( + older_friends_count__gte=2, + ) + self.assertEqual(qs.get(pk__in=qs.values('pk')), self.a1)