Consider these tests:
{{{#!python
# Model Author has `ordering = ["name"]` in its Meta
def test_union_with_select_related_and_order(self):
base_qs = Author.objects.select_related('extra').order_by()
qs1 = base_qs.filter(name="a1")
qs2 = base_qs.filter(name="a2")
self.assertFalse(
bool(
qs1.union(qs2).order_by("pk")
)
)
# first() also calls order_by("pk")
def test_union_with_select_related_and_first(self):
base_qs = Author.objects.select_related('extra')
qs1 = base_qs.filter(name="a1")
qs2 = base_qs.filter(name="a2")
self.assertFalse(
bool(
qs1.union(qs2).first()
)
)
}}}
On Postrgres, both of these pass before the named commit, and error after
it with
{{{
django.db.utils.ProgrammingError: ORDER BY "id" is ambiguous
LINE 1: ...id") WHERE "queries_author"."name" = 'a2') ORDER BY "id" ASC
}}}
On Sqlite, the second test (where ordering from the model is in force)
breaks even before this, with
{{{
django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of
compound statements.
}}}
but on current main, the first breaks too -- this time, with
{{{
django.db.utils.OperationalError: 1st ORDER BY term does not match any
column in the result set
}}}
Note that on union queries without {{{select_related()}}}, ordering on
{{{pk}}} works -- many existing tests use it, as well as another test I
added (in the attached diff) just to be sure.
--
Ticket URL: <https://code.djangoproject.com/ticket/34123>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* Attachment "union-select-related-tests.diff" added.
Tests to show and investigate the regression