3

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.

5
  • It's not clear what you want. You want the items which are in BOTH lists or any one of the lists? Commented Apr 29, 2021 at 10:53
  • It's like if (key_value == 1) OR (key_value == 2) OR (key_value == 3) Commented Apr 29, 2021 at 10:54
  • Since you use __in it means that from the moment one of the items matches it is sufficient. Commented Apr 29, 2021 at 10:59
  • Thank you for your comment. But then why does it print AND? Commented Apr 29, 2021 at 11:01
  • @sundowatch: because if you make complex queries, the tree will consist out of nodes that each have an operator. Commented Apr 29, 2021 at 11:04

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.