summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--django/db/models/sql/compiler.py7
-rw-r--r--tests/ordering/tests.py5
2 files changed, 11 insertions, 1 deletions
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index e6e840d8ea..8eb40e94af 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -720,7 +720,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(