Opened 14 years ago

Closed 14 years ago

Last modified 11 years ago

#12270 closed (duplicate)

Wrong SQL generated with annotated fields and ORed Q objects

Reported by: Erik Allik Owned by:
Component: Database layer (models, ORM) Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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?

Change History (2)

comment:1 by James Bennett, 14 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #11293.

comment:2 by Anssi Kääriäinen, 11 years ago

Component: ORM aggregationDatabase layer (models, ORM)
Note: See TracTickets for help on using tickets.
Back to Top