pythondjangodjango-q

How to dynamically compose an OR query filter in Django?


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


Solution

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