Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter database with array and OR operator

Tags:

python

django

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.

like image 528
sundowatch Avatar asked Jun 27 '26 20:06

sundowatch


1 Answers

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)
like image 52
Willem Van Onsem Avatar answered Jun 30 '26 10:06

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!