Opened 3 weeks ago

Closed 11 days ago

Last modified 11 days ago

#37350 closed Bug (fixed)

distinct(*fields) does not fathom aliases containing the lookup separator: "__" — at Version 8

Reported by: Jacob Walls Owned by: Juliana Nicacio
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Jacob Walls)

We are gradually improving the situation with respect to the treatment of annotation aliases containing the lookup separator, see ​PR discussion. This ticket is for .distinct(*fields).

When an alias is provided to .distinct(*fields), is it split on LOOKUP_SEP before checking against the annotations map, meaning it will miss an alias that contains it.

Reproducer:

qs = Person.objects.annotate(my__val=models.Value(1)).distinct("my__val")
print(qs)
  File "/django-ref/django/db/models/sql/query.py", line 1854, in names_to_path
    raise FieldError(
django.core.exceptions.FieldError: Cannot resolve keyword 'my' into field. Choices are: id, my__val, name

The helper from 73cc09f14f13fedddc14d6ba5b287cb33c24e4a4 could be used as part of fixing this, so that we don't omit any nuance with FilteredRelation.

Using the lookup separator in an annotation alias sounds a little unorthodox, but it's present in the ​default alias generated by .aggregate(), and we've taken reports on it before. Also, if you let users choose aliases in configurable reports, it's bound to come up, and we've taken issues on that.

Change History (8)

comment:1 by Jacob Walls, 2 weeks ago

Owner: changed from Django Sprints to Juliana Nicacio

Juliana took this on at Django on the Med 2026 in Pescara and almost has a PR ready to go.

comment:2 by David Smith, 2 weeks ago

Triage Stage: Unreviewed → Accepted

comment:3 by Juliana Nicacio, 12 days ago

Has patch: set

comment:5 by Jacob Walls, 12 days ago

Owner: changed from Juliana Nicacio to Juliana Nicacio

comment:6 by Lily, 12 days ago

Triage Stage: Accepted → Ready for checkin

comment:7 by Jacob Walls <jacobtylerwalls@…>, 11 days ago

Resolution: → fixed
Status: assigned → closed

In dffadf6d:

Fixed #37350 -- Made distinct(*fields) resolve aliases containing "".

Made Query.get_names_to_join() preserve annotation aliases and used it
in SQLCompiler.get_distinct() instead of splitting on LOOKUP_SEP.

Thanks Jacob Walls for the report and the suggested approach, and
Annabelle Wiegart for the groundwork in #36945.

comment:8 by Jacob Walls, 11 days ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top