[Answered ]-Q object (creating it with OR connection type at once)

1👍

Hacky:

>>> Q.default = Q.OR
>>> q = Q(title__icontains='r')
>>> q
<Q: (OR: ('title__icontains', 'r'))>

Don’t do this, because you have mutated the Q class for any future (and existing!) users.

More polite:

from django.db.models import Q

class MyQ(Q):
    default = Q.OR

q = MyQ(title__icontains='r')

But you now have an instance of a subclass of Q. That shouldn’t be a problem, really, but it’s actual unnecessary for these simple objects. Here’s a more advanced way:

>>> from django.db.models import Q
>>> q = Q.__new__(Q)
>>> q.default = Q.OR
>>> q.__init__(title__icontains='r')
>>> q
<Q: (OR: ('title__icontains', 'r'))>
>>> Q.default  # existing Q instances are unaffected
u'AND'
👤wim

1👍

I recently found this and my working solution is:

filter_params = Q(
        **{key: value for key, value in filter_params_dict.items()},
        _connector=Q.OR,
    )

return Model.objects.filter(filter_params)

0👍

@wim’s answer is awesome!
Just a little addition:

Creating a new object for Q seem to be failing but you can make do with modifying the default connector with Q.default = Q.OR.

Additionally, you can pass all query parameters at once by doing:

 Model.objects.filter(Q(**query_dict))
 # Make sure to use query dictionary taking note of the fact that simply using
 # Double star operator would produce list values. You can do:
 dictionary = dict(query_dict)
 well_formed = {key: dictionary.get(key)[0] for key in dictionary.keys()}
 result = Model.objects.filter(Q(**query_dict))

Leave a comment