在不使用信号的情况下,在模型保存方法中是否可以检查模型是否正在创建或更新?如果是这样怎么办?
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)
您可以检查主键是否已创建(即不是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)
注意:当您仅检查
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
尝试这样,
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.id:
# updated
else:
# inserted
models.Model.save(self, *args, **kwargs)
根据 Django 文档执行此操作的另一种方法:
def save(self, force_insert=False, force_update=False, *args, **kwargs):
is_create = self._state.adding
if is_create:
# Do create stuff
else:
# Do update stuff
super().save(*args, **kwargs)