From 42c08ee46539ef44f8658ebb1cbefb408e0d03fe Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Wed, 13 May 2020 23:38:29 -0400 Subject: Fixed #31566 -- Fixed aliases crash when chaining values()/values_list() after annotate() with aggregations and subqueries. Subquery annotation references must be resolved if they are excluded from the GROUP BY clause by a following .values() call. Regression in fb3f034f1c63160c0ff13c609acd01c18be12f80. Thanks Makina Corpus for the report. --- django/db/models/sql/query.py | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'django/db/models/sql/query.py') diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index bb230647eb..f8e146b8de 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -2155,6 +2155,15 @@ class Query(BaseExpression): # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() + elif self.group_by: + # Resolve GROUP BY annotation references if they are not part of + # the selected fields anymore. + group_by = [] + for expr in self.group_by: + if isinstance(expr, Ref) and expr.refs not in field_names: + expr = self.annotations[expr.refs] + group_by.append(expr) + self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) -- cgit v1.3