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: 2023-04-24