Complex Lookups with Q Objects
Standard Django filter arguments are always 'ANDed' together. But what if you need to find users who are either 'Editors' OR 'Admins'? Enter `Q` objects. They allow you to encapsulate conditions and combine them using bitwise operators: `|` (OR), `&` (AND), and `~` (NOT).
Scenario 1: Basic OR Logic
Find records that match one condition OR another.
from django.db.models import Q
# Find products that are Red OR Blue
products = Product.objects.filter(Q(color='Red') | Q(color='Blue'))
Scenario 2: NOT Logic (~)
Find records that do NOT match a condition.
# Find users who are NOT active
inactive_users = User.objects.filter(~Q(is_active=True))
Scenario 3: Complex Nested Logic
Combining AND, OR, and NOT.
# Find (Red OR Blue) items that are ALSO (Cheap AND In Stock)
items = Product.objects.filter(
(Q(color='Red') | Q(color='Blue')) &
(Q(price__lt=50) & Q(stock__gt=0))
)