已捕获,但在django transaction.atomic()块回滚事务中除外

时间:2019-03-02 14:58:27

标签: python django pytest

我有一段这样的代码:

with transaction.atomic():
    for i in some_objects:
        stop_object(i)
    for i in some_objects:
        try:
           activate_object(i)
        except IntegrityError as e:
           pass

Test用py.test编写。由于某种原因,当我捕获IntegrityError时,所有事务都将回滚,并且我具有与以前完全相同的状态。

我确定事务仅应在未捕获的错误上回滚。我想念什么吗?

也不确定如何调试它。如果您有什么想法,请分享。

1 个答案:

答案 0 :(得分:0)

原来需要添加另一个transaction.atomic()块:

with transaction.atomic():
    for i in some_objects:
        stop_object(i)
    for i in some_objects:
        try:
           with transaction.atomic():
               activate_object(i)
        except IntegrityError as e:
           pass