Skip to content

N + 1 Problem

Usually an issue for ORMs

Django and the N+1 Queries Problem

Example: printing all book titles

books = Book.objects.all()
for book in books:
    print(f"{book.title} by {book.author.name}")

results in these queries

SELECT *
FROM books

N queries that look like this

SELECT *
FROM author
WHERE id = ?

Solutions

SQL

Use a view or a join

WITH books AS (
  SELECT *
  FROM authors
)

Django

does ths

  • [[django-orm#select_related]]
  • [[django-orm#prefetch_related]]

GraphQL


Last update: 2022-11-04