Django中mysql使用事務以及批量插入數據

使用事務能夠有效的防止插入數據時出現錯誤影響數據的完整性,再出現錯誤的時候能夠回滾事務,作到要麼所有插入成功要麼所有都不插入python

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)

幾處重點須要注意django

  • 導包,from django.db import transaction
  • 事務的保存點,savePoint = transaction.savepoint()
  • 回滾事務,transaction.rollback(savePoint)
  • 批量插入,bulk_create。批量插入須要提供的數據爲models的實例
相關文章
相關標籤/搜索