How to do OR queries in Django ORM?
In this tutorial, we will learn how to apply OR queries in Django ORM queryset
If your models class name is Enquiry, and field names are Email and State, and more.
A common requirement is performing OR filtering with two or more conditions. Say you want to find all Enquirys with
Email starting with ‘s’ and State starting with ‘Raj’.
Django provides two options.
|, are used as an OR(|) operator
- queryset_1 | queryset_2
- filter(Q(<condition_1>)|Q(<condition_2>)
The SQL query for the above condition will look something like
Similarly our ORM query would look like
Queryset = Enquiry.objects.filter(Email__startswith=”sanju”) | Enquiry.objects.filter(State__startswith=”raj”)
Alternatively, you can use the Q objects.