Django nested transactions - “with transaction.atomic()”

Lara picture Lara · Feb 25, 2014 · Viewed 13.7k times · Source

I would like to know if I have something like this:

def functionA():
    with transaction.atomic():
        #save something
        functionB()

def functionB():
    with transaction.atomic():
        #save another thing

Someone knows what will happen? If functionB fails, functionA will rollback too?

Thank you!

Answer

Kevin Christopher Henry picture Kevin Christopher Henry · Feb 25, 2014

Yes, it will. Regardless of nesting, if an atomic block is exited by an exception it will roll back:

If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

Note also that an exception in an outer block will cause the inner block to roll back, and that an exception in an inner block can be caught to prevent the outer block from rolling back. The documentation addresses these issues. (Or see here for a more comprehensive follow-up question on nested transactions).