Opened 3 hours ago

Last modified 3 hours ago

#37305 new Bug

Annotation aliases can shadow lookups and transforms — at Initial Version

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

Description

.annotate() raises a ValueError when an annotation alias conflicts with a field on the annotated model. However, this is not the case for legitimate lookups and transforms, as demonstrated in this DryORM fiddle.

Here is the reproducer:

  from django.db import models
from django.db.models.expressions import Value
from django.contrib.auth.models import User


class Person(models.Model):
    name = models.CharField(max_length=100)
    creator = models.ForeignKey(User, models.CASCADE, null=True)
    creation_date = models.DateField(auto_now=True)

def run():
    admin = User.objects.create(username="admin")
    Person.objects.create(creator=admin, name="Violet")
    qs1 = Person.objects.all()
    qs2 = Person.objects.annotate(creator__username=Value(1))
    qs3 = Person.objects.annotate(creation_date__year=Value(1))
    # raises ValueError
    # qs4 = Person.objects.annotate(creator=Value(1))
    # qs5 = Person.objects.annotate(creation_date=Value(1))

    # lookup without shadowing
    print(qs1.values("creator__username"))
    # lookup with shadowing
    print(qs2.values("creator__username"))
    # transform without shadowing
    print(qs1.values("creation_date__year"))
    # transform with shadowing
    print(qs3.values("creation_date__year"))

Output:

<QuerySet [{'creator__username': 'admin'}]>
<QuerySet [{'creator__username': 1}]>
<QuerySet [{'creation_date__year': 2026}]>
<QuerySet [{'creation_date__year': 1}]>

The bug was discussed in PR21803 for #36945.

Change History (0)

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