From 037a624120b676858be4b93c4d0adda45916fd2a Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Sun, 7 Jun 2020 16:50:47 +0200 Subject: [PATCH] Fixed #31657 -- Fixed ordering by attnames of self-referential ForeignKeys. --- django/db/models/sql/compiler.py | 7 ++++++- tests/ordering/tests.py | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index abbb1e37cb..686e75c979 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -727,7 +727,12 @@ class SQLCompiler: # If we get to this point and the field is a relation to another model, # append the default ordering for that model unless it is the pk # shortcut or the attribute name of the field that is specified. - if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk': + if ( + field.is_relation and + opts.ordering and + getattr(field, 'attname', None) != pieces[-1] and + name != 'pk' + ): # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins) diff --git a/tests/ordering/tests.py b/tests/ordering/tests.py index aa59b5abb5..61ec3a8592 100644 --- a/tests/ordering/tests.py +++ b/tests/ordering/tests.py @@ -353,6 +353,11 @@ class OrderingTests(TestCase): ['Article 2', 'Article 1'], attrgetter('headline'), ) + self.assertQuerysetEqual( + Article.objects.filter(author__isnull=False).order_by('author__editor_id'), + ['Article 1', 'Article 2'], + attrgetter('headline'), + ) def test_order_by_f_expression(self): self.assertQuerysetEqual(