导入
from dajngo.db import transaction
使用
装饰器用法:
from django.db import transaction
@transaction.atomic
def viewfunc(request):
......
with上下文管理:
from django.db import transaction
def viewfunc(request):
......
with transaction.atomic():
......
举例
save_id = transaction.savepoint()
transaction.savepoint_rollback(save_id)
transaction.savepoint_commit(save_id)
class OrderCommitView(LoginRequiredJSONMixin, View):
"""订单提交"""
def post(self, request):
"""保存订单信息和订单商品信息"""
with transaction.atomic():
save_id = transaction.savepoint()
try:
order = OrderInfo.objects.create(
...
)
...
for ...
if ...:
transaction.savepoint_rollback(save_id)
return ...
except Exception as e:
logger.error(e)
transaction.savepoint_rollback(save_id)
return ...
transaction.savepoint_commit(save_id)
return ...
|