#35830: Queryset Union doesn't persist column names
-------------------------------------+-------------------------------------
Reporter: Paul Landon Tuckett | Owner: (none)
Type: Bug | Status: closed
Component: Database layer | Version: 4.2
(models, ORM) |
Severity: Normal | Resolution: invalid
Keywords: orm, database, | Triage Stage:
queryset, union, sql | Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by Simon Charette):
* resolution: => invalid
* status: new => closed
Comment:
By [
https://docs.djangoproject.com/en/5.1/internals/contributing/triaging-
tickets/#bisecting-a-regression bisecting the changes since 3.2] I
identified 70499b25c708557fb9ee2264686cd172f4b2354e as the change that
introduced the aliasing in order to resolve #34123.
The problem it addresses arise when using `select_related` in queryset
that use union as when it's the case and an ambiguous alias is referenced
for ordering purposes. For example if you do
{{{#!python
base = Book.objects.select_related("author")
base.filter(rating__gt=3).union(base.filter(title__contains="Foo")).order_by("id")
}}}
The generated outer `ORDER BY` clause cannot simply reference `"id"` as
it's ambiguous whether it's `
book.id` or `
author.id` so `
book.id` must be
aliased.
It it understood that only ambiguous column names that are referenced by
`ORDER BY` absolutely need to be aliased but it was much easier to
systematically alias all columns instead.
So to answer your question it is expected that the SQL changed and since
it doesn't change the semantic of the query it is not considered a bug. If
you care about the exact name returned from the query you should resort to
`values` instead.
--
Ticket URL: <
https://code.djangoproject.com/ticket/35830#comment:3>