在Django中的commit_on_success块内调用transaction.commit()

时间:2014-12-05 08:58:08

标签: python mysql django celery

我的代码如下:

@transaction.commit_on_success()
def foo():
    # Performs various database operations and may raise exception
    do_stuff()

    my_object = MyModel.objects.create()

    # Commit transaction so Celery task will see the newly created object
    transaction.commit()

    # Async call Celery task that does something with the new object
    my_celery_task.delay(my_object.id)

这是否符合我的预期,即:

  • 如果没有异常发生,transaction.commit()执行提交
  • 如果do_stuff()引发异常,则回滚事务

我在使用Django 1.4和MySQL。

2 个答案:

答案 0 :(得分:0)

是。根据Django的文档:

  

如果函数返回成功,那么Django将提交所有工作   在那个时候在函数内完成。如果该功能提出了   但是,例外情况是,Django将回滚该交易。

来自here

答案 1 :(得分:0)

如果视图正常返回,

transaction.commit_on_success()将提交,如果引发异常则返回。在你的情况下,它应该“工作”,但可能不是最好的解决方案 - 因为你必须手动提交,你可能更好地使用transaction.commit_manually()https://docs.djangoproject.com/en/1.4/topics/db/transactions/#django.db.transaction.commit_manually):

@transaction.commit_manually()
def foo():
    try:
        # Performs various database operations and may raise exception
        do_stuff()
        my_object = MyModel.objects.create()

    except Exception, e:
        # oops, let's forget about it
        transaction.rollback()
        raise

    else:
        # Commit transaction so Celery task will see the newly created object
        transaction.commit()
        # Async call Celery task that does something with the new object
        my_celery_task.delay(my_object.id)