Opened 9 years ago

Closed 8 years ago

#26108 closed New feature (wontfix)

New method for returning OR querysets

Reported by: Andy Harb Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Anssi Kääriäinen Triage Stage: Someday/Maybe
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It would be nice if you guys created a new method that would allow for OR querysets to be returned.

Right now you can use <model>.objects.filter() in conjunction with the q() method but this is limiting since you have to have all the ORs in a single filter statement. If you where to chain another filter statement the two would be ANDed.

It would be helpful to have another method that would OR the chained results together. This is helpful when you have conditional cases and need to build the queryset up.

Example:
Say i have an object I'm querying and the query looks like this so far:

query = <model>.objects.filter( (Q(id=2) & Q(state=1)) | (Q(id=3) & (state = 2)) ... )

Now lets say I want to append another OR to the end of the query if the current logged in user is and admin. Currently I would have to write a conditional statement and duplicate the query in two places except the query with the if user.is_admin would have some additional conditions.

It would be ideal if we could just append another statement with an OR to the current query:
example : query.include( Q(id=8) & Q(state=3))

This would allow greater flexibility and prevent wet code.

Change History (6)

comment:1 by Simon Charette, 9 years ago

Did you try combining the two querysets using the the pipe operator?

Model.objects.filter(Q(id=2) & Q(state=1)) | Model.objects.filter(Q(id=8) & Q(state=3))

in reply to:  1 comment:2 by Andy Harb, 9 years ago

Replying to charettes:

Did you try combining the two querysets using the the pipe operator?

Model.objects.filter(Q(id=2) & Q(state=1)) | Model.objects.filter(Q(id=8) & Q(state=3))

Yes that works however it doesn't resolve the initial request. Basically if you use ORs you have to have the entire set in a single filter method call. If you chain another .filter to the above it will ANDed it not OR it

comment:3 by Tim Graham, 9 years ago

Cc: Anssi Kääriäinen added

Anssi, any comments?

comment:4 by Anssi Kääriäinen, 9 years ago

This feature is somewhat straightforward to add, so I don't see much technical problems with this.

I don't recall ever having a need for this, so for that reason a mild -0. I guess we could ask around django-developers if there is enough support for this.

comment:5 by Tim Graham, 9 years ago

Triage Stage: UnreviewedSomeday/Maybe

Andy, could you start a thread on the DevelopersMailingList as Anssi suggested?

comment:6 by Tim Graham, 8 years ago

Resolution: wontfix
Status: newclosed

Closing in absence of further discussion.

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