You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django嵌套事务(with transaction.atomic()):内层回滚是否触发外层回滚?

Django嵌套事务:内层函数回滚会影响外层吗?

当然会!如果你的functionB执行失败触发回滚,外层的functionA也会跟着回滚——只要嵌套事务里任意一个函数抛出未处理的异常,整个事务链都会回滚。

这一点Kevin Christopher Henry已经明确给出了结论:

是的,只要任一函数中发生异常,两者都会回滚。

Django的官方文档也对嵌套事务的行为做了清晰说明:

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. Conversely, if an exception is raised in an inner block and not handled, the transaction will be rolled back to the savepoint established at the start of the inner block, and the exception will propagate to the outer block.

简单来说,嵌套的transaction.atomic()并不是独立的事务单元,它们共享同一个顶层事务上下文。内层的异常会向上传播,触发整个事务的回滚,不会出现内层回滚但外层操作保留的情况。

内容的提问来源于stack exchange,提问作者melodibit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:33:11