django-bitfield
django-bitfield copied to clipboard
Invalid reference in sub-query
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.
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.