0
壓倒一切的在Django的1.4我有類似下面的代碼中兩個不同的交易: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(MyModel, self).save(*args, **kwargs)
do_other_things()
except:
transaction.rollback()
raise
else:
transaction.commit()
obj2 = MySecondModel(mymodel = self, foo = "bar")
obj2.save()
class MySecondModel(models.Model):
myModelId = models.ForeignKey(MyModel)
# other fields defining this model
正如你可以看到,創建MyModel
類的對象後,我還必須創建MySecondModel
類的另一個對象,該對象引用了第一個對象。
在上面的代碼中,如果在obj2.save()
期間發生錯誤,將無法回滾第一個事務。
我該如何處理這兩個事務作爲一個獨特的原子事務?
也許[這個答案](http://stackoverflow.com/a/30516268/3945375)可以幫助 – Gocht
我不能在Django 1.4 – floatingpurr
使用'@ transaction.atomic'以前有[commit_on_success](https://docs.djangoproject.com/en/1.4/topics/db/transactions/#django.db.transaction.commit_on_success)。它有幫助嗎? – Gocht