Junior — Middle
Can you explain what the Q operator in Django ORM is and how it is used to build queries?
sobes.tech AI
Answer from AI
In Django ORM, the Q operator is used to construct complex queries with logical operations (AND, OR, NOT) that cannot be expressed with simple filter arguments.
Q allows combining conditions, for example, to retrieve objects that satisfy one of several conditions.
Example usage:
from django.db.models import Q
# Get users whose name is 'John' or age is greater than 30
users = User.objects.filter(Q(name='John') | Q(age__gt=30))
# Exclude users named 'Alice'
users = User.objects.filter(~Q(name='Alice'))
Thus, Q helps build flexible and readable queries with logical operations, extending the capabilities of the standard filter.