[Django]-Django filter database with array and OR operator

4πŸ‘

βœ…

As you see it’s an AND operator. I want to filter with OR operator within this array. How can I implement this?

The AND is simply the default connector if want to add extra Q objects. But the __in lookup [Django-doc] will succeed from the moment that the key_value field has one of the items in the list as value.

We can construct this with an OR, we can set the _connector parameter, and this then produces:

>>> arr = [1,2,3,4,5]
>>> Q(key_value__in=arr, _connector=Q.OR)
<Q: (OR: ('key_value__in', [1, 2, 3, 4, 5]))>

but the two are equivalent, both have only one condition, so the _connector does not matter.

Using a connector can be useful however. If we have for example:

# both conditions should be satisfied
Q(Q(foo=1), Q(bar=2), _connector=Q.AND)

whereas if one of the conditions is sufficient, we can work with:

# both conditions should be satisfied
Q(Q(foo=1), Q(bar=2), _connector=Q.OR)

Leave a comment