From bdcda1ca9ba254743269e482384c2711ac34b1f1 Mon Sep 17 00:00:00 2001
From: "arsalan.ghassemi" <arsalan.ghassemi-ext@johnpaul.com>
Date: Tue, 23 Nov 2021 18:22:52 +0100
Subject: [PATCH] Fixed #33309 -- Fixed QuerySet.distinct() crash on mixed case
 annotation.

---
 django/db/models/sql/compiler.py  | 2 +-
 tests/distinct_on_fields/tests.py | 8 +++++++-
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index 73cf2c5f62..69a2d9298f 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -754,7 +754,7 @@ class SQLCompiler:
             targets, alias, _ = self.query.trim_joins(targets, joins, path)
             for target in targets:
                 if name in self.query.annotation_select:
-                    result.append(name)
+                    result.append(self.connection.ops.quote_name(name))
                 else:
                     r, p = self.compile(transform_function(target, alias))
                     result.append(r)
diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py
index 5404c3eb41..a34c67016f 100644
--- a/tests/distinct_on_fields/tests.py
+++ b/tests/distinct_on_fields/tests.py
@@ -1,5 +1,5 @@
 from django.db import connection
-from django.db.models import CharField, Max
+from django.db.models import CharField, F, Max
 from django.db.models.functions import Lower
 from django.test import TestCase, skipUnlessDBFeature
 from django.test.utils import register_lookup
@@ -149,3 +149,9 @@ class DistinctOnTests(TestCase):
         """
         staff = Staff.objects.distinct('name').order_by('name', '-organisation').get(name='p1')
         self.assertEqual(staff.organisation, 'o2')
+
+    def test_distinct_on_mixed_case_annotation(self):
+        qs = Staff.objects.annotate(
+            nAmEAlIaS=F('name'),
+        ).distinct('nAmEAlIaS').order_by('nAmEAlIaS')
+        self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1])