[Django]-Nested manually commited transactions in Django

4👍

You must be careful here, the DB commit/rollback is connection level, if You have something like this:

@transaction.commit_manually
def foo():
   bar()
   transaction.rollback()

@transaction.commit_manually
def bar()
   #some db op
   transaction.commit()

#running
foo()

changes to the database will be commited, You should put @transaction.commit_manually on top level functions. In django 1.6 transaction.atomic decorator was introduced which generally provides what you are looking for:

atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point

On the other hand You just make rollbacks it should be OK (if you want to stick to 1.4), as long as the commit is on the top level only, but it’s best to keep the transaction management on one level in this case (for example raising Exceptions and handling them in foo())

Leave a comment