How to dynamically compose an OR query filter in Django

0 votes

From an example you can see a multiple OR query filter:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

For example, this results in:

[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]

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))

Aug 3, 2020 in Python by kartik
• 37,510 points
5,012 views

1 answer to this question.

+1 vote

Hello @kartik,

You could chain your queries as follows:

values = [1,2,3]

# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]

# Take one Q object from the list
query = queries.pop()

# Or the Q object with the ones remaining in the list
for item in queries:
    query |= item

# Query the model
Article.objects.filter(query)

Hope this is helpfull!!

Thank You!!

answered Aug 3, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to call function that takes an argument in a Django template?

Hello @kartik, You cannot call a function that ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
12,470 views
0 votes
1 answer

How do I filter query objects by date range in Django?

Hello @kartik, Use Sample.objects.filter(date__range=["2020-01-01", "2020-01-31"]) Or if you are just ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,880 points
33,045 views
0 votes
1 answer

How to change the file name of an uploaded file in Django?

Hello @kartik, The basic way is import os os.rename('a.txt', 'b.html') For ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,880 points
4,216 views
0 votes
1 answer

How to combine two or more querysets in a Django view?

Hello @kartik, Concatenating the querysets into a list ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,880 points
6,576 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,095 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,245 views
0 votes
1 answer

How to query as GROUP BY in django?

Hii, Django does not support free group by ...READ MORE

answered Apr 23, 2020 in Python by Niroj
• 82,880 points
5,820 views
0 votes
1 answer

How to check if an element is present in a Django queryset?

Hello @kartik, You can use the following code: if ...READ MORE

answered May 27, 2020 in Python by Niroj
• 82,880 points
14,221 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP