ORM N+1 query (ARCH2079)
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.
Incorrect
Section titled “Incorrect”def list_authors(): return [ book.author.name for book in Book.objects.all() ]Correct
Section titled “Correct”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.