Django嵌套事务处理.atomic未轧制b

2024-06-16 11:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在两个不同的数据库中有两个逻辑连接的实例。我希望它们都被保存或回滚。但是如果我在外部块中引发异常-嵌套的Transaction.atomic将不会回滚,但为什么呢?在

根据文档:

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.

def __commit_to_db(self, mesure, mdm_mesure):
    try:
        with transaction.atomic():
            mesure.save()
            with transaction.atomic(using='mdm'):
                mdm_mesure.save()
            raise Exception('oops')
    except (keyboardInterrupt, SystemExit):
        raise
    except BaseException as error:
        MainLoger.log_error(error)
    return

Tags: an数据库savewitherrorbe逻辑block
1条回答
网友
1楼 · 发布于 2024-06-16 11:50:30

事务是数据库级功能。因此,尽管您正在嵌套Python代码,但每个数据库实际上都获得了独立于其他数据库的自己的事务。Django中没有跨数据库的嵌套事务。在

你必须以某种方式重组你的代码。例如,将代码放在两个atomic()块中可以:

try:
    with transaction.atomic():
        with transaction.atomic(using='mdm'):
            mesure.save()
            mdm_mesure.save()

            # neither transaction will commit
            raise Exception('oops')
except Exception:
    pass

相关问题 更多 >