From 0f843fdd5b9b2f2307148465cd60f4e1b2befbb4 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Sat, 4 Jan 2020 20:49:11 +0100 Subject: [PATCH] Fixed #31136 -- Disabled grouping by aliases on QuerySet.values()/values_list(). MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regression in fb3f034f1c63160c0ff13c609acd01c18be12f80. Thanks Sigurd Ljødal for the report. --- django/db/models/sql/query.py | 4 +++- docs/releases/3.0.3.txt | 4 ++++ tests/aggregation/tests.py | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index fc423b6acf..f96a0a6e2d 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -2095,7 +2095,9 @@ class Query(BaseExpression): if self.group_by is True: self.add_fields((f.attname for f in self.model._meta.concrete_fields), False) - self.set_group_by() + # Disable GROUP BY aliases to avoid orphaning references to the + # SELECT clause which is about to be cleared. + self.set_group_by(allow_aliases=False) self.clear_select_fields() if fields: diff --git a/docs/releases/3.0.3.txt b/docs/releases/3.0.3.txt index ecc5ba9294..61ef456d93 100644 --- a/docs/releases/3.0.3.txt +++ b/docs/releases/3.0.3.txt @@ -12,3 +12,7 @@ Bugfixes * Fixed a regression in Django 3.0 that caused a crash when subtracting ``DateField``, ``DateTimeField``, or ``TimeField`` from a ``Subquery()`` annotation (:ticket:`31133`). + +* Fixed a regression in Django 3.0 where ``QuerySet.values()`` and + ``values_list()`` crashed if a queryset contained an aggregation and + ``Exists()`` annotation (:ticket:`31136`). diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index dd30f57bed..f523b3ca35 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1151,6 +1151,20 @@ class AggregateTestCase(TestCase): ) self.assertTrue(publisher_qs.exists()) + def test_aggregation_exists_annotation(self): + published_books = Book.objects.filter(publisher=OuterRef('pk')) + publisher_qs = Publisher.objects.annotate( + published_book=Exists(published_books), + count=Count('book'), + ).values_list('name', flat=True) + self.assertCountEqual(list(publisher_qs), [ + 'Apress', + 'Morgan Kaufmann', + "Jonno's House of Books", + 'Prentice Hall', + 'Sams', + ]) + @skipUnlessDBFeature('supports_subqueries_in_group_by') def test_group_by_subquery_annotation(self): """