有时数据的更新修改涉及到多张表的更改,但因为某一环节的出错导致关联数据不能同时更新,为了避免这种问题的出现,可以使用事物(transaction)来解决
Models:
from django.db import models class UserInfo(models.Model): username = models.CharField(max_length=32) email = models.EmailField(max_length=64) class Dept(models.Model): title = models.CharField(max_length=32)
Urls:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/$', views.test), ]
Views:
from django.shortcuts import render, HttpResponse from . import models def test(request): try: from django.db import transaction # 导入事务 with transaction.atomic(): user_obj = models.UserInfo.objects.create(username='Lena', email='example@live.com') dept_obj = models.Dept.objects.create(title='IT') except Exception as e: return HttpResponse('error happened, db rollback') return HttpResponse('OK')
事务的应用需要数据库引擎的支持——Innodb
user_obj和dept_obj的创建需要同时完成,其中一个操作行为的出错都不会实现user_obj和dept_obj的创建