from django.db import transaction
from django.http import HttpResponse
from django.utils.decorators import method_decorator
# 类中添加装饰器,保证在该类中所有的数据库操作都在一个事物中
@method_decorator(transaction.atomic, name='dispatch')
class MyView1(object):
def get(self, request):
return HttpResponse('GET')
def post(self, request):
return HttpResponse('POST')
class MyView2(object):
# 保证在该函数中所有的数据库操作都在一个事物中
@transaction.atomic
def post(self, request):
# 设置事物保存点(可设多个)
t1 = transaction.savepoint()
# 如果有异常情况可回滚到指定的保存点
transaction.savepoint_rollback(t1)
# 如果没有异常可提交事物
transaction.savepoint_commit(t1)
return HttpResponse('POST')