[Fixed]-Nested transaction.atomic() context manager avoid rollback when outer transaction fail

1👍

First of all, since you added @transaction.atomic to some_method if an Exception occurs anywhere inside, everything will be rolled back.

Now, if you remove the decorator and raise the Exception inside the atomic block you more or less get what you wanted : b will be commited, a not.

def some_method(request):
    b.save()

    with transaction.atomic():
        a.save()
        raise Exception('')

In this case, if you raise the Exception outside the block, everything (before the Exception) will be commited (no Exception raised inside a transaction)

I believe that the documentation excerpt refers to the following case :

def funA():
    with transaction.atomic():
        funB()
        #code A

def funB():
    with transaction.atomic():
        #code B

If an Exception occurs in code A, everything in code B will be rolled back.

👤zxzak

Leave a comment