2015-06-08 52 views
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()期間發生錯誤,將無法回滾第一個事務。

我該如何處理這兩個事務作爲一個獨特的原子事務?

+0

也許[這個答案](http://stackoverflow.com/a/30516268/3945375)可以​​幫助 – Gocht

+0

我不能在Django 1.4 – floatingpurr

+1

使用'@ transaction.atomic'以前有[commit_on_success](https://docs.djangoproject.com/en/1.4/topics/db/transactions/#django.db.transaction.commit_on_success)。它有幫助嗎? – Gocht

回答

0

正如Gocht在該問題的評論中所建議的,Django 1.4中的一個解決方案是使用@transaction.commit_on_success()。該代碼可能是這樣的:

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

class MyModel(models.Model): 
    # model definition 

    @transaction.commit_on_success() 
    def save(self, *args, **kwargs): 
     try: 
      super(MyModel, self).save(*args, **kwargs) 
      do_other_things() 
      obj2 = MySecondModel(mymodel = self, foo = "bar") 
      obj2.save() 
     except: 
      print 'exception' 
      raise 
     else: 
      print 'job done' 



class MySecondModel(models.Model): 
    myModelId = models.ForeignKey(MyModel) 
    # other fields defining this model