Junior — Middle
How are Q-queries implemented and used in Django to form complex search conditions?
sobes.tech AI
Answer from AI
In Django, the Q class from the django.db.models module is used to construct complex search conditions. It allows combining conditions using logical operators AND (&), OR (|), and negation (~). This is especially useful when building dynamic or complex queries that cannot be expressed with simple filters.
Example of usage:
from django.db.models import Q
# Find objects where the name field equals 'John' OR the age field is greater than 30
results = MyModel.objects.filter(Q(name='John') | Q(age__gt=30))
# Negation of a condition: all except those with is_active=True
results = MyModel.objects.filter(~Q(is_active=True))
Thus, Q allows building flexible and readable database queries.