From an example you can see a multiple OR query filter:
JavaScript
x
2
1
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
2
For example, this results in:
JavaScript
1
2
1
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
2
However, I want to create this query filter from a list. How to do that?
e.g. [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
Advertisement
Answer
You could chain your queries as follows:
JavaScript
1
15
15
1
values = [1,2,3]
2
3
# Turn list of values into list of Q objects
4
queries = [Q(pk=value) for value in values]
5
6
# Take one Q object from the list
7
query = queries.pop()
8
9
# Or the Q object with the ones remaining in the list
10
for item in queries:
11
query |= item
12
13
# Query the model
14
Article.objects.filter(query)
15