Opened 5 years ago

Closed 5 years ago

#20874 closed Bug (fixed)

Nested subqueries have conflicting alias prefixes

Reported by: Anssi Kääriäinen Owned by: nobody
Component: Database layer (models, ORM) Version: master
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


Currently the ORM has a way to bump table alias prefixes for subqueries. This means that for example alias T0 would be turned to U0. Unfortunately the current way doesn't work when nesting multiple queries, that is in cases like:

qs1 = MyModel.objects.all()
qs2 = MyModel.objects.filter(pk__in=qs1)
qs3 = MyModel.objects.filter(pk__in=qs2)

for qs2 the qs1 gets bumped to U-prefixes. But qs2 gets bumped *again* to U-prefixes in qs3. Luckily this doesn't usually matter that much in current Django, as for example " IN (SELECT FROM sometable u0) does work. Later on, if EXISTS queries are going to be more common this will become more important as "WHERE EXISTS (SELECT ... WHERE = doesn't work at all.

Change History (2)

comment:1 Changed 5 years ago by Anssi Kääriäinen

Has patch: set
Triage Stage: UnreviewedReady for checkin

Patch available at

I think this one is ready for checkin, but as the fix is nontrivial I will leave this open for reviews.

comment:2 Changed 5 years ago by Anssi Kääriäinen <akaariai@…>

Resolution: fixed
Status: newclosed

In dcdc579d162b750ee3449e34efd772703592faca:

Fixed #20874 -- bump_prefix() in nested subqueries

Also made some cleanup to build_filter() code by introducing submethods
solve_lookup_type() and prepare_lookup_value().

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