关于python:django模型:不推荐在手动提交时管理事务

Django models: managing transactions when commit_manually is deprecated

我在运行Django 1.4.11。我以类似于以下代码的方式超越了django模型的save()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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实现相同的逻辑?


相同的逻辑如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()装饰器:

1
2
3
4
5
6
7
8
9
10
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__上提交事务,并在出现异常时回滚。


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

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