Django 模型:不推荐使用 commit_manually 时管理事务

Django models: managing transactions when commit_manually is deprecated

我正在 运行宁 Django 1.4.11。我以类似于以下代码的方式覆盖了 Django 模型的 save() 方法:

from django.db import models
from django.db import transaction

class MyModel(models.Model):
    # model definition

    @transaction.commit_manually
    def save(self, *args, **kwargs):
        try:
            super(self.__class__, self).save(*args, **kwargs)
            foo() # do_other_things
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

当我 运行 我的代码时,有时我会在 Apache 日志中看到这条消息:

RemovedInDjango18Warning: commit_manually is deprecated in favor of set_autocommit.

如何实现与 set_autocommit 相同的逻辑?

对于您给出的示例,您可以使用 transaction.atomic 。如果代码成功,整个事务将被提交。如果出现异常,将回滚更改。

@transaction.atomic
def save(self, *args, **kwargs):
    super(self.__class__, self).save(*args, **kwargs)
    foo() # do_other_things

相同的逻辑如下所示:

from django.db import models
from django.db import transaction

class MyModel(models.Model):
    # model definition

    def save(self, *args, **kwargs):
        transaction.set_autocommit(False)
        try:
            super(MyModel, self).save(*args, **kwargs)
            foo() # do_other_things
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()
        finally:
            transaction.set_autocommit(True)

但是,这等同于使用 atomic() 装饰器:

from django.db import models
from django.db import transaction

class MyModel(models.Model):
    # model definition

    @transaction.atomic
    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)
        foo() # do_other_things

这将在成功 __exit__ 时提交事务,并在出现异常时回滚。