启用事务(方式一)
Django create
update
delete
操作时自行加行级互斥锁(InnoDB引擎)
from django.db import transaction
# 只对这个视图函数启用事务
@transaction.atomic
def atomic1(request):
# 一堆ORM操作
pass
return HttpResponse('ok')
# CBV
class TestView(View):
@transaction.atomic
def post(self, request, *args, **kwargs):
# 一堆ORM操作
pass
return HttpResponse('ok')
启用事务(方式二)
from django.db import transaction
# 上下文管理器形式加事务
def atomic2(request):
with transaction.atomic():
try:
# 一堆ORM操作
except Exception:
pass
return HttpResponse('ok')
设置保存点
from django.db import transaction
# 上下文管理器形式加事务
def atomic2(request):
with transaction.atomic():
try:
# 一堆ORM操作1
# 设置事务回滚的标记点
sid = transation.savepoint()
# 一堆ORM操作2
except Exception:
# 回滚到ORM操作1之后
transation.savepoint_rallback(sid)
return HttpResponse('ok')