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(