How to perform OR condition in Django Queryset with code example?

In Django, you can perform an OR condition in a queryset using the Q object. The Q object allows you to build complex queries with logical OR and AND operators. Here’s how you can use the Q object to perform an OR condition in a queryset with a code example:

Let’s say you have a model named Product and you want to retrieve products that match either a certain category or have a specific price range. Here’s how you can achieve that using the Q object:

from django.db.models import Q
from myapp.models import Product # Replace with your actual app and model names

# Retrieve products matching either a certain category or a specific price range
products = Product.objects.filter(Q(category='Electronics') | Q(price__range=(100, 500)))

# Print the matching products
for product in products:
print(product.name, product.category, product.price)

In this example, the Q object is used to build a query that retrieves products with a category of ‘Electronics’ OR products with a price in the range of 100 to 500. The | operator represents the logical OR condition between the two Q objects.

You can use the Q object to build more complex queries with multiple conditions involving logical OR and AND operators. Just remember to enclose each condition within a separate Q object and combine them using the appropriate logical operators (| for OR, & for AND).

Keep in mind that the Q object can be used in various ways within queryset filters to create complex queries based on your specific requirements.