From 8de4ca74ba49b3f97a252e2b9d385cb2e70c442c Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Fri, 30 Apr 2021 13:37:19 +0200 Subject: [PATCH] Fixed #32693 -- Quoted and lowercased generated column aliases. --- django/db/models/sql/compiler.py | 5 ++++- tests/queries/tests.py | 13 ++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 5fd37423de..7264929da8 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -554,7 +554,10 @@ class SQLCompiler: if alias: s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias)) elif with_col_aliases: - s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx) + s_sql = '%s AS %s' % ( + s_sql, + self.connection.ops.quote_name('col%d' % col_idx), + ) col_idx += 1 params.extend(s_params) out_cols.append(s_sql) diff --git a/tests/queries/tests.py b/tests/queries/tests.py index 44f6206b44..f6437e1175 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -7,7 +7,7 @@ from threading import Lock from django.core.exceptions import EmptyResultSet, FieldError from django.db import DEFAULT_DB_ALIAS, connection -from django.db.models import Count, Exists, F, OuterRef, Q +from django.db.models import Count, Exists, F, Max, OuterRef, Q from django.db.models.expressions import RawSQL from django.db.models.sql.constants import LOUTER from django.db.models.sql.where import NothingNode, WhereNode @@ -1855,6 +1855,17 @@ class Queries6Tests(TestCase): [self.t5, self.t4], ) + def test_col_alias_quoted(self): + with CaptureQueriesContext(connection) as captured_queries: + self.assertEqual( + Tag.objects.values('parent').annotate( + tag_per_parent=Count('pk'), + ).aggregate(Max('tag_per_parent')), + {'tag_per_parent__max': 2}, + ) + sql = captured_queries[0]['sql'] + self.assertIn('AS %s' % connection.ops.quote_name('col1'), sql) + class RawQueriesTests(TestCase): @classmethod