1
0
mirror of https://github.com/django/django.git synced 2025-02-05 23:15:29 +00:00

Fixed #36065 -- Fixed ordering by expression referencing composite primary key.

Thanks Jacob Walls for the report and test and Csirmaz Bendegúz for the review.
This commit is contained in:
Simon Charette 2025-01-07 00:02:31 -05:00 committed by Sarah Boyce
parent 7617d5be94
commit 42e8f264ce
3 changed files with 26 additions and 2 deletions

View File

@ -1861,6 +1861,16 @@ class OrderBy(Expression):
return [self.expression] return [self.expression]
def as_sql(self, compiler, connection, template=None, **extra_context): def as_sql(self, compiler, connection, template=None, **extra_context):
if isinstance(self.expression, ColPairs):
sql_parts = []
params = []
for col in self.expression.get_cols():
copy = self.copy()
copy.set_source_expressions([col])
sql, col_params = compiler.compile(copy)
sql_parts.append(sql)
params.extend(col_params)
return ", ".join(sql_parts), params
template = template or self.template template = template or self.template
if connection.features.supports_order_by_nulls_modifier: if connection.features.supports_order_by_nulls_modifier:
if self.nulls_last: if self.nulls_last:

View File

@ -1117,10 +1117,9 @@ class SQLCompiler:
) )
return results return results
targets, alias, _ = self.query.trim_joins(targets, joins, path) targets, alias, _ = self.query.trim_joins(targets, joins, path)
target_fields = composite.unnest(targets)
return [ return [
(OrderBy(transform_function(t, alias), descending=descending), False) (OrderBy(transform_function(t, alias), descending=descending), False)
for t in target_fields for t in targets
] ]
def _setup_joins(self, pieces, opts, alias): def _setup_joins(self, pieces, opts, alias):

View File

@ -1,3 +1,4 @@
from django.db.models import F
from django.test import TestCase from django.test import TestCase
from .models import Comment, Tenant, User from .models import Comment, Tenant, User
@ -55,3 +56,17 @@ class CompositePKOrderByTests(TestCase):
self.comment_1, # (1, 1) self.comment_1, # (1, 1)
), ),
) )
def test_order_comments_by_pk_expr(self):
self.assertQuerySetEqual(
Comment.objects.order_by("pk"),
Comment.objects.order_by(F("pk")),
)
self.assertQuerySetEqual(
Comment.objects.order_by("-pk"),
Comment.objects.order_by(F("pk").desc()),
)
self.assertQuerySetEqual(
Comment.objects.order_by("-pk"),
Comment.objects.order_by(F("pk").desc(nulls_last=True)),
)