From b15f162f252610e3b510ade465549769ab4356cf Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Mon, 27 Feb 2023 01:10:19 -0500 Subject: [PATCH] Fixed #34372 -- Fixed queryset crash on order by aggregation using OrderBy. Regression in 278881e37619278789942513916acafaa88d26f3 caused by a lack of expression copying when an OrderBy expression is explicitly provided. Thanks Jannis Vajen for the report and regression test. --- django/db/models/sql/compiler.py | 2 ++ tests/ordering/tests.py | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 919e951fa2..e1a240dec3 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -358,11 +358,13 @@ class SQLCompiler: if ( field.nulls_first is None and field.nulls_last is None ) or self.connection.features.supports_order_by_nulls_modifier: + field = field.copy() field.expression = select_ref # Alias collisions are not possible when dealing with # combined queries so fallback to it if emulation of NULLS # handling is required. elif self.query.combinator: + field = field.copy() field.expression = Ref(select_ref.refs, select_ref.source) yield field, select_ref is not None continue diff --git a/tests/ordering/tests.py b/tests/ordering/tests.py index 7ff38acc4a..b29404ed77 100644 --- a/tests/ordering/tests.py +++ b/tests/ordering/tests.py @@ -638,3 +638,9 @@ class OrderingTests(TestCase): .first(), self.a1, ) + + def test_order_by_expr_query_reuse(self): + qs = Author.objects.annotate(num=Count("article")).order_by( + F("num").desc(), "pk" + ) + self.assertCountEqual(qs, qs.iterator())