#37305: Annotation aliases can shadow lookups and transforms
-------------------------------------+-------------------------------------
Reporter: Annabelle Wiegart | Type: Bug
Status: new | Component: Database
| layer (models, ORM)
Version: 6.1 | Severity: Normal
Keywords: annotate, alias | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
.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 [
https://dryorm.xterm.info
/shadowing-lookups-transforms DryORM fiddle].
Here is the reproducer:
{{{#!div style="font-size: 80%"
{{{#!python
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:
{{{#!div style="font-size: 80%"
{{{#!python
<QuerySet [{'creator__username': 'admin'}]>
<QuerySet [{'creator__username': 1}]>
<QuerySet [{'creation_date__year': 2026}]>
<QuerySet [{'creation_date__year': 1}]>
}}}
}}}
The bug was discussed in
[
https://github.com/django/django/pull/21803#discussion_r3823261022
PR21803] for #36945.
--
Ticket URL: <
https://code.djangoproject.com/ticket/37305>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.