How to use orwhere Query in Django?

Hi Dev,
I will explain step by step tutorial python django filter q example. This post will give you simple example of python django filter q example tutorial. you'll learn How to perform OR condition in django queryset. if you want to see example of python django filter or query example then you are a right place.
We can use the Q() object to implement complex SQL queries. We can use a Q() object to represent a SQL statement which can be utilized for some database operations.
This operator allows to define and reuse the conditions and it also allows to combine them with operators like “OR” and “AND“.
Follow bellow tutorial step of django query orwhere example.
Employee Table:
In this example,this QuerySet with return a new QuerySet where the name of the object starts with “B“. Here is the result of the below example.
python manage.py shell
Now, we will execute the following example.
>>> from myApp.models import Employee >>> from django.db.models import Q >>> >>> queryset = Employee.objects.filter( ... Q(firstname__startswith="B") ... ).values() >>> >>> print(queryset)Output
[ { 'id': 1, 'firstname': 'Bhavesh', 'lastname': 'Sonagra' } ]Example : 2
In this second example we cannot directly use the OR operator to filter the QuerySet. For this implementation, we have to use the Q() object. By using the Q() object in the filter method, we will be able to use the OR operator between the Q() objects.
python manage.py shell
Now, we will execute the following example.
>>> >>> from myApp.models import Employee >>> from django.db.models import Q >>> >>> queryset = Employee.objects.filter( ... Q(firstname__startswith="B")|Q(lastname__startswith="P") ... ).values() >>> >>> print(queryset)Output
[ { 'id': 1, 'firstname': 'Bhavesh', 'lastname': 'Sonagra' }, { 'id': 2, 'firstname': 'Vishal', 'lastname': 'Patel' } ]
I Hope It will help you....