使用事務可以有效的防止插入數據時出現錯誤影響數據的完整性,再出現錯誤的時候可以回滾事務,做到要麼全部插入成功要麼全部都不插入
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的實例