What does `transaction.atomic()` actually guarantee?


What Django transaction.atomic() guarantees, and the two things that surprise people. Outside a block Django runs in autocommit; entering the outermost atomic block opens a real transaction, leaving it normally commits, and letting an exception propagate out rolls back every write made inside, which means the try must sit outside the with statement or the block exits cleanly and commits partial work. Nested atomic calls do not open nested transactions, because databases do not support them: the inner call creates a savepoint, so an inner failure can be caught and discarded while the outer block keeps its earlier writes and commits. Explains why a database error such as IntegrityError leaves the transaction unusable, making the next query raise TransactionManagementError, and why wrapping the risky statement in its own atomic block fixes it by rolling back to a savepoint. Includes runnable Django code and real output, plus oncommit, ATOMICREQUESTS, and selectforupdate.

Комментарии

Комментариев пока нет. Будьте первым, кто поделится своим мнением.
Средний
0,0 (0)

Автор

Software engineer and the creator of the Bytestark learning platform