From 10866a10fe9f0ad3ffdf6f93823aaf4716e6f27c Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Thu, 19 Mar 2020 19:54:36 +0100 Subject: Fixed #31377 -- Disabled grouping by aliases on QuerySet.values()/values_list() when they collide with field names. Regression in fb3f034f1c63160c0ff13c609acd01c18be12f80. Thanks Holovashchenko Vadym for the report. --- django/db/models/sql/query.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (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 78c4f47b5b..9fe0c9a656 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1927,6 +1927,19 @@ class Query(BaseExpression): primary key, and the query would be equivalent, the optimization will be made automatically. """ + # Column names from JOINs to check collisions with aliases. + if allow_aliases: + column_names = set() + seen_models = set() + for join in list(self.alias_map.values())[1:]: # Skip base table. + model = join.join_field.related_model + if model not in seen_models: + column_names.update({ + field.column + for field in model._meta.local_concrete_fields + }) + seen_models.add(model) + group_by = list(self.select) if self.annotation_select: for alias, annotation in self.annotation_select.items(): @@ -1940,7 +1953,7 @@ class Query(BaseExpression): warnings.warn(msg, category=RemovedInDjango40Warning) group_by_cols = annotation.get_group_by_cols() else: - if not allow_aliases: + if not allow_aliases or alias in column_names: alias = None group_by_cols = annotation.get_group_by_cols(alias=alias) group_by.extend(group_by_cols) -- cgit v1.3