1.导入模块
from django.db import transaction
2.使用方法
with transaction.atomic():
User.objects.create(name='lqz',pwd='123')
Teacher.objects.create(name='1qz',pwd='123')
注意:需要自己捕捉异常
有多个sql语法时使用,保证同时成功或一个都不成功
try:
with transaction.atomic():
User.objects.create(name='lqz',pwd='123')
Teacher.objects.create(name='1qz2')
except Exception as e:
print(e)
#with语句中有异常,sql语句也不会执行成功
from django.db import transaction
try:
with transaction.atomic():
User.objects.create(name='zb',pwd='123')
print(5/0)
except Exception as e:
print(e)
转载于:https://www.cnblogs.com/robert-zhou/p/10672635.html