Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid reference in sub-query #31

Open
kelvin-wong opened this issue May 27, 2013 · 1 comment
Open

Invalid reference in sub-query #31

kelvin-wong opened this issue May 27, 2013 · 1 comment

Comments

@kelvin-wong
Copy link

q1 = ModelOne.objects.filter(flags=ModelOne.flags.flag)
q2 = ModelTwo.objects.filter(id__in=q1)

The produced sql will be like this,

SELECT "model_one"."id",  FROM "model_one" WHERE ("model_one"."id" IN (SELECT U0."id" FROM "model_two" U0 WHERE (U0."flags" =  ("model_two"."flags" | 1)))

From the sql, the condition in sub-query is refer to "model_two" not U0.
This will produce invalid reference table in the query.

@moggers87
Copy link

A general workaround for this bug is to use F expressions:

from django.db.models import F

q1 = ModelOne.objects.filter(flags=F('flags').bitor(ModelOne.flags.flag))
q2 = ModelTwo.objects.filter(id__in=q1)

This will produce the correct SQL.

It's also worth noting that this bug only affects Django >1.6 when multiple table aliases are in use (e.g. joins). I've tried debugging this issue further and I wouldn't be surprised if this is actually a bug in Django.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants