Skip to content

Lazy Load In Loop (ARCH2059)

Key python.orm.lazy-load-in-loop · Severity warning · Category orm

Accessing a lazily-loaded relation on each iterated element is the runtime trigger of N+1 when eager loading was omitted. Load the relation up front.

for book in Book.objects.all():
print(book.author.name) # a lazy SELECT per book
for book in Book.objects.select_related("author"):
print(book.author.name) # author loaded in one JOIN

Eager-load the relation accessed in the loop with select_related / prefetch_related.