Code

Ticket #11916: ticket_11916.diff

File ticket_11916.diff, 1.9 KB (added by tobias, 4 years ago)

patch with test

Line 
1diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
2--- a/django/db/models/sql/compiler.py
3+++ b/django/db/models/sql/compiler.py
4@@ -473,9 +473,8 @@
5             group_by = self.query.group_by or []
6 
7             extra_selects = []
8-            for extra_select, extra_params in self.query.extra_select.itervalues():
9-                extra_selects.append(extra_select)
10-                params.extend(extra_params)
11+            for extra_select_key in self.query.extra_select.iterkeys():
12+                extra_selects.append(extra_select_key)
13             for col in group_by + self.query.related_select_cols + extra_selects:
14                 if isinstance(col, (list, tuple)):
15                     result.append('%s.%s' % (qn(col[0]), qn(col[1])))
16diff --git a/tests/regressiontests/aggregation_regress/tests.py b/tests/regressiontests/aggregation_regress/tests.py
17new file mode 100644
18--- /dev/null
19+++ b/tests/regressiontests/aggregation_regress/tests.py
20@@ -0,0 +1,27 @@
21+from django.test import TestCase
22+from django.db.models import Count
23+
24+from regressiontests.aggregation_regress.models import *
25+
26+
27+class AggregationTests(TestCase):
28+   
29+    def test_annotate_with_extra(self):
30+        """
31+        Regression test for #11916: Extra params + aggregation creates
32+        incorrect SQL.
33+        """
34+        shortest_book_sql = """
35+        SELECT name
36+        FROM aggregation_regress_book b
37+        WHERE b.publisher_id = aggregation_regress_publisher.id
38+        ORDER BY b.pages
39+        LIMIT 1
40+        """
41+        # tests that this query does not raise a DatabaseError due to the full
42+        # subselect being (erroneously) added to the GROUP BY parameters
43+        qs = Publisher.objects.extra(select={
44+            'name_of_shortest_book': shortest_book_sql,
45+        }).annotate(total_books=Count('book'))
46+        # force execution of the query
47+        list(qs)