简体   繁体   English

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

[英]Django how to check whether a model is being created created or update

Without using signals, within the model save method is it possible to check whether a model is being created created or update? 在不使用信号的情况下,是否可以在模型保存方法中检查是否正在创建模型或创建或更新模型? If so how? 如果可以,怎么办?

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)

You can check whether primary key has been created (ie is not None ): 您可以检查是否已创建主键(即不是None ):

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)

Note : when you check only if id: it would be treated as False in case when the id had value 0 . 注意 :当您检查只有if id:它会被当作False时,如果id有值0 Check this out: 看一下这个:

>>> 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

Try like this, 这样尝试

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

   if self.id:
      # updated
   else:
      # inserted

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM