How to dynamically compose an OR query filter in Django?

51,589

Solution 1

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)

Solution 2

To build more complex queries there is also the option to use built in Q() object's constants Q.OR and Q.AND together with the add() method like so:

list = [1, 2, 3]
# it gets a bit more complicated if we want to dynamically build
# OR queries with dynamic/unknown db field keys, let's say with a list
# of db fields that can change like the following
# list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3']

# init our q objects variable to use .add() on it
q_objects = Q(id__in=[])

# loop trough the list and create an OR condition for each item
for item in list:
    q_objects.add(Q(pk=item), Q.OR)
    # for our list_with_strings we can do the following
    # q_objects.add(Q(**{item: 1}), Q.OR)

queryset = Article.objects.filter(q_objects)

# sometimes the following is helpful for debugging (returns the SQL statement)
# print queryset.query

Solution 3

A shorter way of writing Dave Webb's answer using python's reduce function:

# For Python 3 only
from functools import reduce

values = [1,2,3]

# Turn list of values into one big Q objects  
query = reduce(lambda q,value: q|Q(pk=value), values, Q())  

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

Solution 4

from functools import reduce
from operator import or_
from django.db.models import Q

values = [1, 2, 3]
query = reduce(or_, (Q(pk=x) for x in values))

Solution 5

Maybe it's better to use sql IN statement.

Article.objects.filter(id__in=[1, 2, 3])

See queryset api reference.

If you really need to make queries with dynamic logic, you can do something like this (ugly + not tested):

query = Q(field=1)
for cond in (2, 3):
    query = query | Q(field=cond)
Article.objects.filter(query)
Share:
51,589
Jack Ha
Author by

Jack Ha

Musician and software engineer

Updated on January 07, 2021

Comments

  • Jack Ha
    Jack Ha over 3 years

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

    • Dominic Rodger
      Dominic Rodger about 15 years
      You appear to have asked this twice: stackoverflow.com/questions/852404
    • beruic
      beruic almost 7 years
      For this specific use case you'd probably use Article.objects.filter(pk__in=[1, 2, 3]) in modern django, but the question is still relevant if you want to do something a bit more advanced by OR'ing Q objects together.
  • Jack Ha
    Jack Ha about 15 years
    Thanks! This was what I was looking for :) Didn't know you could do |=
  • chachan
    chachan almost 12 years
    You could also initialize the query using: query = Q()
  • rechie
    rechie over 10 years
    you can make dynamic fields by using **{'fieldname': value}: queries = [Q(**{'fieldname': value}) for value in values]
  • user
    user almost 10 years
    How can you compose raw queries with Django if you want to add optional conditions like above?
  • Theresa Summa
    Theresa Summa almost 9 years
    For newcomers to this thread, like myself, I think this answer should be regarded as the top answer. It is more Djangoesque than the accepted answer. Thank you!
  • wobbily_col
    wobbily_col about 8 years
    Is this documented anywhere? I have been searching for the last 15 minutes, and this is the only thing I can find.
  • Bobort
    Bobort over 7 years
    I would debate that it is more pythonic to use the builtin OR and AND operators (| and &). q_objects |= Q(pk=item)
  • Bobort
    Bobort over 7 years
    You could also use query |= Q(field=cond)
  • Chris
    Chris over 7 years
    Like so much in our industry, it is documented on StackOverflow!
  • Chris
    Chris over 7 years
    You could use q = Q() instead of q = None, then remove the if q is None clause - slightly less efficient but can remove three lines of code. (The empty Q is subsequently merged away when the query is run.)
  • lsowen
    lsowen over 7 years
    Looks like the "builtin" reduce was removed and replaced with functools.reduce. source
  • mpiskore
    mpiskore over 7 years
    Ok, but where does the operator came from?
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams over 7 years
    @mpiskore: Same place as every other Python module: you import it.
  • mpiskore
    mpiskore over 7 years
    funny. that was really my question: in which module/library can I find it? google didn't help much.
  • mpiskore
    mpiskore over 7 years
    oh, I thought it was some sort of Django ORM operator. How silly of me, thanks!
  • Tom Viner
    Tom Viner over 7 years
    Thanks @lsowen , fixed.
  • RL Shyam
    RL Shyam over 7 years
    Perfect! Thank you!
  • eigenein
    eigenein over 5 years
    And it's possible to use operator.or_ instead of the lambda.
  • Wil
    Wil over 5 years
    Worth noting that if list happens to be empty you'll return the equivalent of Article.objects.all(). Easy to mitigate by returning Article.objects.none() for that test though.
  • Mehran Nouri
    Mehran Nouri almost 5 years
    That didn't work for me, I don't know why. queries return zero results for me
  • geekandglitter
    geekandglitter almost 5 years
    After much googling and tearing my hair out, I found this simple, clean solution. Thank you
  • Jonathan Richards
    Jonathan Richards over 4 years
    @Wil you can also initialize q_objects with Q(id__in=[]). It will always fail unless ORed with something and the query optimizer will handle it nicely.
  • Mike
    Mike about 2 years
    This is what I was looking for. Thank you!