Q Object (Django)
A Q object lets you build complex database queries with OR, AND, and NOT logic in the Django ORM. Plain filter() arguments are always ANDed together, so you use Q to express conditions like 'A or B'.
Django
filter(a=1, b=2) means a AND b. To express OR you need Q objects: filter(Q(a=1) | Q(b=2)). You combine them with | for OR, & for AND, and ~ for NOT, and you can group them with parentheses to build arbitrarily complex conditions.
Q objects accept the same field lookups as filter, so Q(title__icontains='django') | Q(body__icontains='django') searches two fields. You can mix Q objects with normal keyword arguments in one filter call, as long as the Q objects come first.
They are the building block for search features where the same term should match any of several fields, and for conditional queries assembled in Python before hitting the database.
Syntax
from django.db.models import Q
filter(Q(a=1) | Q(b=2))Examples
Python
from django.db.models import Q
# match posts whose title OR body contains the term
term = "django"
results = Post.objects.filter(
Q(title__icontains=term) | Q(body__icontains=term)
)
# NOT and AND
Post.objects.filter(~Q(status="draft") & Q(author__name="Ana"))