当前位置:Gxlcms > 数据库问题 > Django数据库--事务及事务回滚

Django数据库--事务及事务回滚

时间:2021-07-01 10:21:17 帮助过:67人阅读

django.db import transaction # open a transaction @transaction.atomic def add_author_views(request): # 自动提交方式 # Author.objects.create(name=u‘wangbaoqiang‘,age=33,email=‘wangbaoqiang@qqq.com‘) author_name = ulinghuchong author = Author(name=author_name,age=26,email=linghuchong@qqq.com) author.save() # transaction now contains author.save() sid = transaction.savepoint() try: count = Count(name=author_name, article_amount=1) count.save() # transaction now contains author.save() and count.save() transaction.savepoint_commit(sid) # open transaction still contains author.save() and count.save() except IntegrityError: transaction.savepoint_rollback(sid) # open transaction now contains only count.save() # 保存author操作回滚后,事务只剩下一个操作 transaction.clean_savepoints() #清除保存点

注意:希望当遇到错误得到回滚的事务一定要放在try里面(如果放在try外面,虽然不会报错,但是是不会执行的)。如上面的例子,如果在给Count表执行插入数据发生错误,就会‘断点’回滚到Count表插入数据前,Author表插入的数据不变。

  

参考文章:https://www.cnblogs.com/thomson-fred/p/10198528.html

Django数据库--事务及事务回滚

标签:执行   https   nsa   实现   部分   行操作   功能   数据库数据   django数据库   

人气教程排行