summaryrefslogtreecommitdiff
path: root/django/db/models/sql
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2023-12-08 02:03:14 -0500
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2023-12-12 05:51:33 +0100
commitb0ad41198b3e333f57351e3fce5a1fb47f23f376 (patch)
treeb68005963b6261679db534b102d4327b584d12e2 /django/db/models/sql
parentfcf95e592774a6ededec35481a2061474d467a2b (diff)
Fixed #34013 -- Added QuerySet.order_by() support for annotation transforms.
Thanks Eugene Morozov and Ben Nace for the reports.
Diffstat (limited to 'django/db/models/sql')
-rw-r--r--django/db/models/sql/compiler.py26
1 files changed, 16 insertions, 10 deletions
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index cb559308cd..10338259d5 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -387,18 +387,24 @@ class SQLCompiler:
True,
)
continue
- if col in self.query.annotations:
- # References to an expression which is masked out of the SELECT
- # clause.
+
+ ref, *transforms = col.split(LOOKUP_SEP)
+ if expr := self.query.annotations.get(ref):
if self.query.combinator and self.select:
+ if transforms:
+ raise NotImplementedError(
+ "Ordering combined queries by transforms is not "
+ "implemented."
+ )
# Don't use the resolved annotation because other
- # combinated queries might define it differently.
- expr = F(col)
- else:
- expr = self.query.annotations[col]
- if isinstance(expr, Value):
- # output_field must be resolved for constants.
- expr = Cast(expr, expr.output_field)
+ # combined queries might define it differently.
+ expr = F(ref)
+ if transforms:
+ for name in transforms:
+ expr = self.query.try_transform(expr, name)
+ if isinstance(expr, Value):
+ # output_field must be resolved for constants.
+ expr = Cast(expr, expr.output_field)
yield OrderBy(expr, descending=descending), False
continue