diff --git a/AUTHORS b/AUTHORS index ddc2c9ee84..a42eabf8db 100644 --- a/AUTHORS +++ b/AUTHORS @@ -618,6 +618,7 @@ answer newbie questions, and generally made Django that much better: Mykola Zamkovoi Nagy Károly Nasimul Haque + Nasir Hussain Natalia Bidart Nate Bragg Neal Norwitz diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index d433d6b8a0..ccb9636503 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -994,6 +994,7 @@ class Subquery(Expression): query which will be resolved when it is applied to that query. """ template = '(%(subquery)s)' + contains_aggregate = False def __init__(self, queryset, output_field=None, **extra): self.queryset = queryset diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index ee3676e64a..df92dba432 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -534,6 +534,18 @@ class BasicExpressionsTests(TestCase): outer = Company.objects.filter(pk__in=Subquery(inner.values('pk'))) self.assertFalse(outer.exists()) + def test_subquery_filter_by_aggregate(self): + Number.objects.create(integer=1000, float=1.2) + Employee.objects.create(salary=1000) + qs = Number.objects.annotate( + min_valuable_count=Subquery( + Employee.objects.filter( + salary=OuterRef('integer'), + ).annotate(cnt=Count('salary')).filter(cnt__gt=0).values('cnt')[:1] + ), + ) + self.assertEqual(qs.get().float, 1.2) + def test_explicit_output_field(self): class FuncA(Func): output_field = models.CharField()