Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter with OR statement

Tags:

python

django

I need to write filter that will check situation like:

if there are an actors with name "John" than return these actors, otherwise search actors with name "David".

Pseudocode may look like:

Actors.filter(name="John" or name="David")

Can i do something like this in Django using one query? or do I have to use if ?

actors = Actor.filter(name="John")
if not actors.exists():
    actors = Actors.filter(name="David")
like image 669
Pawulla Avatar asked Jul 22 '17 11:07

Pawulla


1 Answers

You can use Q objects. Django docs provides a more detailed description about the Q objects. In short, it allows you to do more complex queries like AND, OR queries. For your question specifically you can do like this:

Actor.objects.filter(Q(name="John") | Q(name="David"))

And in general here are some cool stuffs you can do with Q objects.

You can use Q to create dynamic query also. For example:

    import operator
    try:
        from functools import reduce
    except ImportError:  # Python < 3
        pass

    q_list = [Q(question__contains='dinner'), Q(question__contains='meal')]
    Poll.objects.filter(reduce(operator.or_, q_list))

the example in this post is taken from this post.

like image 81
badiya Avatar answered Sep 22 '22 05:09

badiya