Ir al contenido

Write Inside Loop (ARCH2052)

Esta página aún no está disponible en tu idioma.

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.