﻿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
37258	Combining `values()` querysets on a model with `Meta.ordering` crashes	Adam Johnson	Adam Johnson	"Combining querysets restricted with {{{values()}}}/{{{values_list()}}} (e.g. via {{{union()}}}) on a model with {{{Meta.ordering}}} crashes at SQL compilation on Django 6.1 when the default ordering columns are not part of the selected columns:

{{{
django.db.utils.DatabaseError: ORDER BY term does not match any column in the result set.
}}}

Minimal reproduction (crashes on PostgreSQL, MySQL, and Oracle — any backend with {{{supports_slicing_ordering_in_compound=True}}}; the same code works on Django 6.0):

{{{#!python
class Book(models.Model):
    name = models.CharField(max_length=10)
    rank = models.IntegerField()

    class Meta:
        ordering = [""rank""]

Book.objects.values(""name"").union(Book.objects.values(""name""))  # crashes on iteration
}}}

Same for {{{values_list()}}}, and for {{{intersection()}}}/{{{difference()}}}. {{{qs1.union(qs2).values(""name"")}}} doesn't crash but silently adds a spurious {{{__orderbycol2}}} column to the compiled query and result set.

Regression in 087bb9e8f3478d53f12b1737af865992af17c5f2 (Refs #36644 -- Applied default ordering after union()), which sets {{{default_ordering = True}}} on the combined query so that {{{Meta.ordering}}} is applied after the combination. Root cause: for combined queries with a limited list of selected fields, {{{SQLCompiler.get_order_by()}}} cannot inject the implicit ordering columns into the {{{values()}}} parts ({{{has_select_fields}}} guard in {{{django/db/models/sql/compiler.py}}}), so it raises {{{DatabaseError}}}."	Bug	assigned	Database layer (models, ORM)	6.1	Release blocker				Unreviewed	1	0	0	0	0	0
