Django - 引发异常时不会发生回滚

Ram*_*tta 3 python django transactions atomic django-database

设置.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'diva',
    'USER': 'root',
    'PASSWORD': 'admin',
    'ATOMIC_REQUESTS':True,
    'HOST': 'localhost',
    'PORT': '3306',
},
Run Code Online (Sandbox Code Playgroud)

}

视图.py

def create_project(self, request):
    try:
        with transaction.atomic():
               code here
    except Exception as e:
        print "Exception--->",str(e)
        response = {"status":"failed",'response': ugettext("projects.services.create_project.failure")}
        stat = status.HTTP_400_BAD_REQUEST
        return Response(response, status=stat)
Run Code Online (Sandbox Code Playgroud)

在我的代码中,如果它引发 ObjectDoesNotExist 异常 回滚没有发生,任何人都可以用示例解释事务在 django 中的工作原理。

e4c*_*4c5 5

这是正确的。行为 如果发生异常,django 将回滚事务,但该异常必须是 DatabaseError或其子类之一(最明显的是 IntegrityError)

ObjectDoesNotExist不是 DatabaseError 的子类,因此没有理由回滚此事务。

最后但并非最不重要的。不要捕获Exception总是捕获您正在寻找的特定异常。