Opened 4 years ago

Closed 4 years ago

Last modified 14 months ago

#12270 closed (duplicate)

Wrong SQL generated with annotated fields and ORed Q objects

Reported by: RaceCondition 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: UI/UX:


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?

Attachments (0)

Change History (2)

comment:1 Changed 4 years ago by ubernostrum

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #11293.

comment:2 Changed 14 months ago by akaariai

  • Component changed from ORM aggregation to Database layer (models, ORM)

Add Comment

Modify Ticket

Change Properties
<Author field>
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.