django 事务需要引入 from django.db import transaction
用法1:
@transaction.atomic
def func():
# 相关的操作
用法2:
with transaction.atomic():
# 相关的操作
对于函数中存在正常的异常处理的,不能使用方式1。如下实例1,因为 Component 中可能存在与其它表存在关联,存在关联时候就无法删除,处理为捕获异常并提示用户相关信息。由于整个函数被 @transaction.atomic 装饰,数据提交被延后到函数执行完毕,因此异常无法正常捕获,就必须使用实例2的方法。
# 实例1
class ComponentDeleteView(LoginRequiredMixin, View):
@transaction.atomic
def get(self, request):
seq = request.GET.get('seq')
com = Component.objects.get(seq=seq)
try:
com.delete()
new_log = UserOperateLog(xx)
new_log.save()
except Exception:
# 操作
return render(request, 'bom/component_detail.html', {'com': com, 'msg': error_msg})
return HttpResponseRedirect((reverse('bom:component_list')))
# 实例2
class ComponentDeleteView(LoginRequiredMixin, View):
def get(self, request):
seq = request.GET.get('seq')
com = Component.objects.get(seq=seq)
try:
with transaction.atomic():
com.delete()
# 将操作记录添加到日志中
new_log = UserOperateLog(xx)
new_log.save()
except Exception:
# 操作
return render(request, 'bom/component_detail.html', {'com': com, 'msg': error_msg})
return HttpResponseRedirect((reverse('bom:component_list')))