Opened 9 minutes ago

#37559 new Bug

Fieldless values() and values_list() keep a previously selected annotation transform

Reported by: Cleisson Owned by:
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Since 8e3dec67 (#37330), a fieldless values() or values_list() call after values("published", "published__year") also returns the year, where published is an annotation. On 6.1.3, and on main just before that commit, it returned only the model fields and published. Rows get an extra item, and combining the two values() querysets with union() fails because the column counts differ.

from datetime import date

from django.conf import settings

settings.configure(
    INSTALLED_APPS=[],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)

import django

django.setup()

from django.db import connection, models


class Entry(models.Model):
    date = models.DateField()

    class Meta:
        app_label = "example"


with connection.schema_editor() as editor:
    editor.create_model(Entry)
Entry.objects.create(date=date(2026, 1, 1))

entries = Entry.objects.annotate(published=models.F("date"))
selected = entries.values("published", "published__year")
print(entries.values_list().get())
print(selected.values_list().get())
print(Entry.objects.values("date__year").values_list().get())
print(list(selected.values().union(entries.values())))

On main (c2478276), the second line prints (1, datetime.date(2026, 1, 1), datetime.date(2026, 1, 1), 2026), and the union raises OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns. On 6.1.3 and 368bef0b, the second line matches the first and the union returns one row. A transform on a model field doesn't carry over: the third line prints (1, datetime.date(2026, 1, 1)) on all three.

set_values() now stores published__year in self.annotations and adds it to the annotation mask, which #37330 needed so that a later annotate() or values("published__year") can use it. A fieldless values() keeps the mask, so the transform comes back. I'm not sure the extra column is intended. In 6.1, a transform on an annotation in values() only worked when the alias was also selected and its output_field was bound to a model; an ExpressionWrapper annotation raised AttributeError.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top