Complex lookups with Q objects
Keyword argument queries-in filter()
, and others.-are ANDed together. If you need to execute more complex queries (for example, queries with OR
statements), you can use Q objects
.
A Q object
(django.db.models.Q
) is an object used to encapsulate a collection of keyword arguments. These keyword arguments are specified as in Field lookups above.
For example, this Q
object encapsulates a single LIKE
query:
from django.db.models import Q Q(question__startswith='What')
Q
objects can be combined using the &
and |
operators. When an operator is used on two Q
objects, it yields a new Q
object.
For example, this statement yields a single Q
object that represents the OR of two "question__startswith"
queries:
Q(question__startswith='Who') ...
Get Mastering Django: Core now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.