diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index cc4b0c52a66..b270640ea57 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 54836178c48..63dee594643 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)