﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34372	Field position reference for aggregate ends up in group-by clause	Jannis Vajen	Simon Charette	"Changeset 278881e37619278789942513916acafaa88d26f3 introduced a regression. Aggregate queries are rejected by the database due to the aggregated field being added to the GROUP BY clause.

It was difficult for me to pin down, especially because it looks like the error only occurs on the second evaluation of the query. The first query is executed just fine and doesn't contain the position reference to the aggregated field in the GROUP BY, only the second one. Below is a test to reproduce the behaviour:

{{{#!patch
diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py
index bfb3919b23..05122db956 100644
--- a/tests/aggregation_regress/tests.py
+++ b/tests/aggregation_regress/tests.py
@@ -1321,6 +1321,16 @@ class AggregationTests(TestCase):
             lambda b: (b.name, b.authorCount),
         )
 
+    def test_quoting_aggregate_order_by_f(self):
+        author = Author.objects.get(name=""Peter Norvig"")
+        qs = (
+            author.book_set.all()
+            .annotate(num=Count(""authors""))
+            .order_by(F(""num"").desc())
+        )
+        list(qs.iterator())
+        list(qs.iterator())
+
     def test_stddev(self):
         self.assertEqual(
             Book.objects.aggregate(StdDev(""pages"")),
}}}"	Bug	closed	Database layer (models, ORM)	4.2	Release blocker	fixed	orm aggregation		Ready for checkin	1	0	0	0	0	0
