Aller au contenu

Write Inside Loop (ARCH2052)

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

Key python.orm.write-inside-loop · Severity error · Category orm

Calling save() / commit() on every loop iteration produces one DB round-trip per row instead of a batch. Batch the writes instead.

for row in rows:
user = User(name=row.name)
user.save() # a separate INSERT per row
users = [User(name=row.name) for row in rows]
User.objects.bulk_create(users) # one batched INSERT

Accumulate objects and persist them once outside the loop with bulk_create.