在不使用信号的情况下,在模型保存方法中是否可以检查是创建模型还是更新?如果是这样的话?
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)
答案 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)