【Django杂记】django Django的事务操作方法
Django框架本身提供了两种事务操作的方法(针对mysql)
从django1.6开始,Django的事务操作方法主要通过django.db.transation模块完成
启用事务用法1:
from django.db import transaction
from rest_framework.views import APIView
class OrderAPIView(APIView):
@transaction.atomic # 开启事务,当方法执行完以后,自动提交事务
def post(self, request):
pass 启用事务用法2:
from django.db import transaction
from rest_framework.views import APIView
class OrderAPIView(APIView):
def post(self, request):
with transaction.atomic(): # 开启事务,当with语句执行完成以后,自动提交事务
pass # 数据库操作在使用事务过程中,有时候会出现异常,当出现异常的时候,我们需要让程序停下来,同时回滚事务。
from django.db import transaction
from rest_framework.views import APIView
class OrderAPIView(APIView):
def post(self, request):
with transaction.atomic():
# 设置事务回滚的标记点
sid = transation.savepoint()
...
try:
...
except:
transation.savepoint_rallback(sid)本文来自博客园,作者:郭祺迦,转载请注明原文链接:https://www.cnblogs.com/guojie-guojie/p/16330179.html

浙公网安备 33010602011771号