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 in Python by kartik
• 27,140 points
58 views

1 answer to this question.

0 votes

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 by Niroj
• 58,500 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 in Python by Niroj
• 58,500 points
200 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 in Python by Niroj
• 58,500 points
1,448 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 in Python by Niroj
• 58,500 points
90 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 in Python by Niroj
• 58,500 points
201 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 in Python by Niroj
• 58,500 points
179 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 in Python by Niroj
• 58,500 points
80 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 in Python by Niroj
• 58,500 points
123 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 in Python by Niroj
• 58,500 points
688 views