Similar to older answers, but a bit simpler, without the lambda...
To filter these two conditions using OR
:
Item.objects.filter(Q(field_a=123) | Q(field_b__in=(3, 4, 5, ))
To get the same result programmatically:
filter_kwargs = {
'field_a': 123,
'field_b__in': (3, 4, 5, ),
}
list_of_Q = [Q(**{key: val}) for key, val in filter_kwargs.items()]
Item.objects.filter(reduce(operator.or_, list_of_Q))
operator
is in standard library: import operator
From docstring:
or_(a, b) -- Same as a | b.
For Python3, reduce
is not a builtin any more but is still in the standard library: from functools import reduce
P.S.
Don't forget to make sure list_of_Q
is not empty - reduce()
will choke on empty list, it needs at least one element.