使用事务可以有效的防止插入数据时出现错误影响数据的完整性,再出现错误的时候可以回滚事务,做到要么全部插入成功要么全部都不插入
from django.views import View
from main import models
from django.db import transaction
import json
class BillTypeAdd(View):
'''
新增账单类别api
'''
@transaction.atomic # 事务修饰器
def post(self, request):
status = False
data = request.POST.get('data')
# 用于事务保存
savePoint = None
try:
data = json.loads(data)
# 用于存储实例对象
BillTypeModels = []
for item in data:
item.pop('id')
BillTypeModels.append(models.BillType(**item))
savePoint = transaction.savepoint() # 事务保存点
models.BillType.objects.bulk_create(BillTypeModels)
status = True
except Exception as error:
if savePoint:
# 回滚事务
transaction.rollback(savePoint)
status = error.__str__()
return HttpResponse(status)
几处重点需要注意
- 导包,from django.db import transaction
- 事务的保存点,savePoint = transaction.savepoint()
- 回滚事务,transaction.rollback(savePoint)
- 批量插入,bulk_create。批量插入需要提供的数据为models的实例