2014-02-13 73 views
0

如果不使用信號,在模型保存方法中可以檢查模型是否正在創建或更新?如果是這樣如何?Django如何檢查模型是否正在創建或更新

def save(self, force_insert=False, force_update=False, *args, **kwargs): 
     """ 
     Override of save() method which is executed the same 
     time the ``pre_save``-signal would be 
     """ 

     models.Model.save(self, *args, **kwargs) 
+4

如果它有'self.id',它是一個更新。否則,這是一個新的對象。 –

+0

這將工作! – Prometheus

回答

1

嘗試這樣,

def save(self, force_insert=False, force_update=False, *args, **kwargs): 

    if self.id: 
     # updated 
    else: 
     # inserted 

    models.Model.save(self, *args, **kwargs) 
2

您可以檢查主鍵是否已經創建(即不無):

def save(self, force_insert=False, force_update=False, *args, **kwargs): 

    if self.pk is None: 
     # model is going to be created 
    else: 
     # model will be updated 

    super(YourModelClass, self).save(*args, **kwargs) 

注意:當您檢查只有if id:它將被視爲False,以防止id的值爲0。看看這個:

>>> id = 0 
>>> if id: 
...  print("ID is set to %s" % id) 
... # no result, but the value is set! 

>>> id = 1 
>>> if id: 
...  print("ID is set to %s" % id) 
... 
ID is set to 1 

>>> id = 0 
>>> if id is not None: 
...  print("ID is set to %s" % id) 
... 
ID is set to 0 
相關問題