django实现事务


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

python3
try:
    with transaction.atomic():
        User.objects.create(name='zb',pwd='123')
        print(5/0)
except Exception as e:
    print(e)

python2
with transaction.commit_on_success():
      


posted @ 2019-04-08 18:53  robertzhou  阅读(417)  评论(0编辑  收藏  举报