Opened 10 years ago

Closed 10 years ago

#3691 closed (duplicate)

Telling Q Objects to split up foreign keys (extension of #3592)

Reported by: axiak@… Owned by: Adrian Holovaty
Component: Database layer (models, ORM) Version: master
Severity: Keywords: Q, QSplit, m2m
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


This is not a duplicate of #3592.

I was working with some of the things in #3592, and it seems from chatting on IRC that people really want a way to do ANDs on a m2m field without the Q objects subsuming them into one JOIN.

Suppose you have Article and Tag, where Article has a m2m relation with Tag (related_name = 'tag'). If I run:

from django.db.models.query import Q
Article.objects.filter(Q(tag__value = 'A') & Q(tag__value = 'B'))
> # no results

I would expect to get no results (there are no tags with both a value of 'A' and 'B').
However, I *would* like to somehow get a list of articles with tags meeting that criteria. Using the patch, you can:

from django.db.models.query import Q,QSplit
Article.objects.filter(QSplit(Q(tag__value = 'A')) & QSplit(Q(tag__value = 'B'))) 
> # articles with both tags

So now they are split into different Tag entries.

This isn't meant to be used in django. Just for people if they need it before the queryset refactoring. Also, this seems like it would be useful in the final version, so it's here for reference.

Attachments (1)

ticket_3691_axiak.diff (7.2 KB) - added by axiak@… 10 years ago.
Patch to django for QSplit

Download all attachments as: .zip

Change History (2)

Changed 10 years ago by axiak@…

Attachment: ticket_3691_axiak.diff added

Patch to django for QSplit

comment:1 Changed 10 years ago by Malcolm Tredinnick

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Resolution: duplicate
Status: newclosed

The actual bug involved here is the same as in #1801 (that one talks about whole QuerySet objects, not Q() objects, but hte underlying logic is the same).

The workaround might be useful for some people, but please put that in the wiki, rather than the ticket tracker, since otherwise there would be no way to effectively resolve this ticket.

Note: See TracTickets for help on using tickets.
Back to Top