python / beginner
Snippet
Filtering with OR using Q objects
Standard Django filters use AND logic. Q objects allow you to use the | (OR) operator to build complex queries that check multiple conditions.
snippet.py
1
2
3
4
5
from django.db.models import Qfrom .models import Product# Find products that are either out of stock OR priced under 10items = Product.objects.filter(Q(stock=0) | Q(price__lt=10))
django
Breakdown
1
from django.db.models import Q
Imports the Q class needed for complex query lookups.
2
Q(stock=0) | Q(price__lt=10)
Uses the pipe symbol to define an OR condition between two filters.