sundowatch
sundowatch

Reputation: 3093

Django filter database with array and OR operator

I'm trying to filter database with Q objects. Here is my code:

arr = [1,2,3,4,5]

filter_obj = Q(key_value__in=arr)
print(filter_obj)   # (AND: ('key_value__in', [u'1', u'2', u'3', u'4', u'5']))

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

Note: We don't know the items in array.

Upvotes: 3

Views: 274

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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)

Upvotes: 4

Related Questions