Wrong SQL generated with annotated fields and ORed Q objects
|Reported by:||RaceCondition||Owned by:|
|Component:||Database layer (models, ORM)||Version:||1.1|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
These are the models I have:
A Language model, and
Text with fkeys to Language: language (related_name='texts1' and target_language (related_name='texts2').
I want to do a query on languages that have either at least one item in texts1 or in texts2.
from django.db.models import Count, Q languages = Language.objects.all().annotate(num_texts1=Count('texts1'), num_texts2=Count('texts2')) languages = languages.filter(Q(num_texts1__gt=0) | Q(num_texts2__gt=0))
Now I'd assume the generated query contains a HAVING clause with two conditions ORed in it, but no. This is what _as_sql() returns:
('SELECT U0."id" FROM "localsite_language" U0 LEFT OUTER JOIN "localsite_text" U1 ON (U0."id" = U1."target_language_id") LEFT OUTER JOIN "localsite_text" U2 ON (U0."id" = U2."language_id") GROUP BY U0."id", U0."name", U0."slug", U0."original_name" HAVING (COUNT(U1."id") > %s AND COUNT(U2."id") > %s )', (0, 0))
In the HAVING clause there's an AND instead of an OR which causes wrong query results. Am I missing something here myself or is this a bug?