Django query filters allow you to retrieve, filter, and manipulate database records using Django’s ORM (QuerySet API). Filters convert Pythonic queries into SQL queries automatically.
Author
Benedict Thekkel
1. Basic Query Filtering
Filters are applied using .filter(), .exclude(), and .get() on Django QuerySets.
Method
Description
filter(**conditions)
Returns records matching the conditions.
exclude(**conditions)
Returns records not matching the conditions.
get(**conditions)
Returns a single object matching the condition (raises MultipleObjectsReturned or DoesNotExist).
Example Usage
from myapp.models import Employee# Get all employees with age 30employees = Employee.objects.filter(age=30)# Get all employees EXCEPT those with age 30employees_exclude = Employee.objects.exclude(age=30)# Get a single employee with a unique field (e.g., email)employee = Employee.objects.get(email="john@example.com")
2. Field Lookups (Operators)
Django provides lookup expressions to perform SQL-like queries.
# Employees in HR department with age > 30Employee.objects.filter(department="HR", age__gt=30)
3.2 OR Condition (Q objects)
from django.db.models import Q# Employees in HR OR IT departmentEmployee.objects.filter(Q(department="HR") | Q(department="IT"))
3.3 NOT Condition (~Q)
# Employees NOT in HR departmentEmployee.objects.filter(~Q(department="HR"))
4. Ordering and Limiting Results
Method
Description
Example
order_by()
Orders by field
.order_by("age")
order_by("-field")
Orders in descending
.order_by("-salary")
reverse()
Reverses existing order
.order_by("age").reverse()
distinct()
Removes duplicate records
.distinct()
count()
Counts total rows
.count()
first()
First object
.first()
last()
Last object
.last()
values()
Returns a dictionary
.values("name", "age")
# Get first 10 employees ordered by salary (descending)Employee.objects.order_by("-salary")[:10]
5. Query Aggregation (Sum, Avg, Min, Max, Count)
from django.db.models import Avg, Sum, Count, Min, Max# Average salaryEmployee.objects.aggregate(Avg("salary"))# Total salaryEmployee.objects.aggregate(Sum("salary"))# Count employees in IT departmentEmployee.objects.filter(department="IT").count()
6. Prefetching and Optimizing Queries
6.1 Select Related (One-to-One, ForeignKey)
# Optimized query (joins related tables)Employee.objects.select_related("department").all()
6.2 Prefetch Related (Many-to-Many, Reverse Relations)
# Optimized query for many-to-many fieldsEmployee.objects.prefetch_related("projects").all()
7. Raw SQL Queries (When Filters Are Not Enough)
from django.db import connectionquery ="SELECT * FROM myapp_employee WHERE age > %s"with connection.cursor() as cursor: cursor.execute(query, [30]) results = cursor.fetchall()
8. Common Mistakes and Best Practices
Avoid fetching all records unnecessarily
# BAD: Loads entire table into memoryemployees = Employee.objects.all()for e in employees:print(e.name)
Use efficient filtering
# GOOD: Filters data in the databaseemployees = Employee.objects.filter(age__gt=30)
Avoid multiple queries inside loops
for emp in Employee.objects.all():print(emp.department.name) # Triggers multiple DB queries
Use select_related to optimize joins
for emp in Employee.objects.select_related("department").all():print(emp.department.name) # Reduces queries
Final Thoughts
Use filter() for precise queries.
Use Q for OR conditions.
Use select_related() and prefetch_related() for optimized queries.
Use values() and only() to fetch only required fields.
Use .count() instead of len(queryset) to avoid unnecessary loading.
Mastering Django filters enhances database efficiency and performance! 🚀