Middle
How to use the 'or' operator in QuerySet?
sobes.tech AI
Answer from AI
For the logical 'or' operator in QuerySet, the Q object is used.
# Example of using the 'or' operator
from django.db.models import Q
# Get objects where the name is 'Alice' or age is greater than 30
queryset = MyModel.objects.filter(Q(name='Alice') | Q(age__gt=30))
You can combine Q objects with other filters.
# Get objects where the name is 'Bob' and (city is 'New York' or country is 'USA')
queryset = MyModel.objects.filter(name='Bob', Q(city='New York') | Q(country='USA'))
It is also possible to combine multiple Q objects.
# Get objects where (name is 'Charlie' or age is less than 20) and city is 'London'
queryset = MyModel.objects.filter(Q(name='Charlie') | Q(age__lt=20), city='London')