django中ORM的事务操作

在django的ORM中,有两种使用事务的方式(注意,mysql需要是innodb引擎)

装饰器

from django.db import transaction
@transaction.atomic
def viewfunc(request):
    # 下面的代码在一个事务中执行,一但出现异常,整个函数中所有的数据库操作全部都会回滚
    ...

上下文管理

from django.db import transaction

class ViewClass(View)
    def get(self, request)
        # 下面的代码在自动提交模式下执行(Django的默认模式)。
        with transaction.atomic():
            # 下面的代码在一个事务中执行,一但出现异常,整个with函数内部的数据库操作都会回滚
            ...

with 内部最好不要使用try...catch...模块,否则可能会影响django的事务异常判断

猜你喜欢

转载自www.cnblogs.com/longyunfeigu/p/9109967.html