๐Ÿ“ Django

select_related and prefetch_related

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
276
๐ŸŒณ
Level
Advanced

Query optimization when working with related objects.

The N+1 Problem

# Bad: 1 query for tasks + N queries for each project
tasks = Task.objects.all()
for task in tasks:
    print(task.project.name)  # a new SQL query every time!
# Good: one query with JOIN
tasks = Task.objects.select_related('project', 'owner')
for task in tasks:
    print(task.project.name)  # already loaded
    print(task.owner.username)  # already loaded

Works with: ForeignKey, OneToOneField.

# Two queries: tasks + all tags
tasks = Task.objects.prefetch_related('tags')
for task in tasks:
    for tag in task.tags.all():  # already loaded
        print(tag.name)

Works with: ManyToManyField, reverse ForeignKey via related_name.

Combining Both

tasks = Task.objects.select_related('project', 'owner').prefetch_related('tags')

Prefetch with Filtering

from django.db.models import Prefetch

projects = Project.objects.prefetch_related(
    Prefetch(
        'tasks',
        queryset=Task.objects.filter(status='todo').order_by('priority'),
        to_attr='todo_tasks',  # store in attribute
    )
)

for project in projects:
    print(project.todo_tasks)  # list, not a queryset

When to Use Which

Situation Solution
task.project.name (FK) select_related('project')
task.tags.all() (M2M) prefetch_related('tags')
project.tasks.all() (reverse FK) prefetch_related('tasks')
FK + filter on related prefetch_related(Prefetch(...))

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 280
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 566
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 316
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum