Django如何检查是否正在创建模型或更新

时间:2014-02-13 13:31:42

标签: python django django-models

在不使用信号的情况下,在模型保存方法中是否可以检查是创建模型还是更新?如果是这样的话?

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)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

试试这个,

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

   if self.id:
      # updated
   else:
      # inserted

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