Aller au contenu

ORM N+1 query (ARCH2079)

Ce contenu n’est pas encore disponible dans votre langue.

Key python.performance.orm-n-plus-one · Severity error · Category performance

Looping over a query result and touching each item’s relation issues one extra query per row (N+1). Eager-load the relation with select_related/prefetch_related.

def list_authors():
return [
book.author.name
for book in Book.objects.all()
]
def list_authors():
return [
book.author.name
for book in Book.objects.select_related("author").all()
]

Eager-load related data in a single query with select_related or prefetch_related.