diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index bd723f69d9..ceaf65cd4d 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -630,7 +630,7 @@ class Query(object): else: col, order = get_order_dir(field, asc) elt = qn2(col) - if distinct and elt not in select_aliases: + if distinct and col not in select_aliases: ordering_aliases.append(elt) result.append('%s %s' % (elt, order)) self.ordering_aliases = ordering_aliases diff --git a/tests/regressiontests/extra_regress/models.py b/tests/regressiontests/extra_regress/models.py index 8ee06bed32..1d31fb267a 100644 --- a/tests/regressiontests/extra_regress/models.py +++ b/tests/regressiontests/extra_regress/models.py @@ -98,4 +98,13 @@ True >>> Order.objects.extra(where=["username=%s"], params=["fred"], tables=["auth_user"]).order_by('created_by') [] +# Regression test for #8819: Fields in the extra(select=...) list should be +# available to extra(order_by=...). +>>> User.objects.extra(select={'extra_field': 1}).distinct() +[] +>>> User.objects.extra(select={'extra_field': 1}, order_by=['extra_field']) +[] +>>> User.objects.extra(select={'extra_field': 1}, order_by=['extra_field']).distinct() +[] + """}