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

时间:2017-03-22 07:38:23

标签: python django transactions atomicity django-database

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'diva',
    'USER': 'root',
    'PASSWORD': 'admin',
    'ATOMIC_REQUESTS':True,
    'HOST': 'localhost',
    'PORT': '3306',
},

}

views.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)

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

1 个答案:

答案 0 :(得分:1)

这是正确的。行为django将回滚事务,如果发生异常但该异常必须是DatabaseError或其中一个子类(最值得注意的是IntegrityError)

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

最后但并非最不重要。不要抓住Exception总是抓住你想要的特定例外。