Django 嵌套事务 - “with transaction.atomic()”

问题描述 投票:0回答:2

我想知道我是否有这样的事情:

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

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

有人知道会发生什么吗?如果 functionB 失败,functionA 也会回滚吗?

谢谢!

django transactions nested atomic
2个回答
69
投票

是的,会的。无论嵌套如何,如果原子块因异常退出它将回滚

如果代码块成功完成,更改将提交到数据库。如果出现异常,更改将回滚。

还要注意,外部块中的异常会导致内部块回滚,并且可以捕获内部块中的异常以防止外部块回滚。该文档解决了这些问题。 (或者参见 here 了解有关嵌套事务的更全面的后续问题)。


0
投票
with transaction.atomic(): # Outer atomic, start a new transaction
    transaction.on_commit(foo)
    try:
        with transaction.atomic(): # Inner atomic block, create a savepoint
            transaction.on_commit(bar)
            raise SomeError() # Raising an exception - abort the savepoint
    except SomeError:
        pass
# foo() will be called, but not bar()
© www.soinside.com 2019 - 2024. All rights reserved.