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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With