django 数据库 mysql 事务 处理
显式控制事务¶
Django 提供了一个 API 控制数据库事务。
- atomic(using=None, savepoint=True)¶
- 
原子性是数据库事务的定义属性。 atomic允许创建代码块来保证数据库的原子性。如果代码块成功创建,这个变动会提交到数据库。如果有异常,变动会回滚。atomic块可以嵌套。在这个例子里,当内部块成功完成时,如果在稍后外部块里引发了异常,则仍可回滚到最初效果。atomic既可用作 decorator:: :from django.db import transaction @transaction.atomic def viewfunc(request): # This code executes inside a transaction. do_stuff() 也可用作 context manager:: : from django.db import transaction def viewfunc(request): # This code executes in autocommit mode (Django's default). do_stuff() with transaction.atomic(): # This code executes inside a transaction. do_more_stuff() 在 try/except 块中使用装饰器 atomic来允许自然处理完整性错误:from django.db import IntegrityError, transaction @transaction.atomic def viewfunc(request): create_parent() try: with transaction.atomic(): generate_relationships() except IntegrityError: handle_exception() add_children() 事务回滚¶第一个选项是回滚整个事务。比如: a.save() # Succeeds, but may be undone by transaction rollback try: b.save() # Could throw exception except IntegrityError: transaction.rollback() c.save() # Succeeds, but a.save() may have been undone 调用 transaction.rollback()回滚整个事务。任何未提交的数据库操作会被丢弃。在这个例子里,a.save()做的改变会丢失,即使操作本身没有引发错误。保存点回滚¶你可以使用 savepoints 来控制回滚的程度。执行可能失败的数据库操作之前,你可以设置或更新保存点;这样,如果操作失败,你可以回滚单一的错误操作,而不是回滚整个事务。比如: a.save() # Succeeds, and never undone by savepoint rollback sid = transaction.savepoint() try: b.save() # Could throw exception transaction.savepoint_commit(sid) except IntegrityError: transaction.savepoint_rollback(sid) c.save() # Succeeds, and a.save() is never undone 在这个例子里, a.save()将不会在b.save()引发异常的情况下被撤销。声明 : 转载自 Django 官方中文库文档。 链接 : https://docs.djangoproject.com/zh-hans/3.0/topics/db/transactions/#django.db.transaction.rollback 
    邮箱: 1090055252@qq.com
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号