简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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