Back to Articles
2024-02-15

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.

python
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.

python
# 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.

python
# 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))
)