﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34123	Ambiguous aliases in ordering on combined queries with select_related().	Shai Berger	David Sanders	"Ordering on combined queries with {{{select_related()}}} seems to have been slightly broken in [c58a8acd413ccc].

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."	Bug	closed	Database layer (models, ORM)	dev	Release blocker	fixed	select_related	Simon Charette David Sanders	Ready for checkin	1	0	0	0	0	0
