我的代码如下:
@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。
答案 0 :(得分:0)
答案 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)