0
0
Djangoframework~5 mins

Q objects for complex queries in Django

Choose your learning style9 modes available
Introduction

Q objects help you build complex database queries easily. They let you combine conditions with AND, OR, and NOT in a clear way.

When you want to filter database records with multiple conditions combined with OR.
When you need to negate a condition in a query.
When you want to mix AND and OR conditions in a single query.
When simple filter() calls are not enough to express your query logic.
Syntax
Django
from django.db.models import Q

Model.objects.filter(Q(condition1) & Q(condition2) | ~Q(condition3))

Use Q() to wrap each condition.

Combine Q objects with & for AND, | for OR, and ~ for NOT.

Examples
Find records where name is Alice OR Bob.
Django
Q(name='Alice') | Q(name='Bob')
Find records where age is between 18 and 30 (inclusive).
Django
Q(age__gte=18) & Q(age__lte=30)
Find records where is_active is NOT True.
Django
~Q(is_active=True)
Find records in New York AND (status not inactive OR score greater than 50).
Django
Q(city='New York') & (~Q(status='inactive') | Q(score__gt=50))
Sample Program

This example shows how to find people who are either younger than 18 or not active using Q objects combined with OR and NOT.

Django
from django.db import models
from django.db.models import Q

# Sample model
class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    city = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

# Example query using Q objects
# Find people who are either under 18 or not active
query = Person.objects.filter(Q(age__lt=18) | ~Q(is_active=True))

# This would return a QuerySet of matching Person objects
OutputSuccess
Important Notes

Q objects make queries easier to read and maintain when conditions get complex.

Always import Q from django.db.models.

Q objects can be combined in any order using parentheses to control logic.

Summary

Q objects let you build complex queries with AND, OR, and NOT.

Use Q to combine multiple conditions in one filter call.

They help write clear and flexible database queries in Django.