在我们的项目中,我们使用软删除(模型上的is_deleted属性)。 在创建新模型之前,我想首先检查它是否已经存在并删除,如果是这样 - 设置is_deleted = False并保存已存在的模型。 所以我决定覆盖模型'save'方法。 (不是View Create,因为它不仅适用于请求) 问题是为所有操作(创建,更新,删除)调用'save()'。 有没有办法只能在create?
上调用重写方法class Model(BaseModel):
title = models.CharField(max_length=200)
identifier = models.CharField(max_length=15)
def save(self, *args, **kwargs):
try:
existing_model = Model.objects.active_and_deleted().get( identifier=self.identifier)
if self.is_deleted is False:
existing_model.is_deleted = False
existing_model.title = self.title
existing_model.created_at = self.created_at
existing_model.updated_at = self.updated_at
existing_model.created_by = self.created_by
existing_model.deleted_at = None
super(Model, existing_model).save(args, kwargs)
except Model.DoesNotExist:
# in case the Nodel wasn't already exist - continue
pass
super(Model, self).save(*args, **kwargs)
答案 0 :(得分:2)
你的问题的答案,"有没有办法只能在创建时调用被覆盖的方法?"是这样的:
def save(self, *args, **kwargs):
if not self.id:
# Object is a new instance
return super(Model, self).save(*args, **kwargs)
但这里还有其他问题。例如,您的模型不应被命名为#34; Model&#34 ;.
答案 1 :(得分:2)
检查self.pk
是否可以做你想做的事,这是一个例子:
class ModelName(mdoels.Model):
title = models.CharField(max_length=200)
identifier = models.CharField(max_length=15)
def save(self, *args, **kwargs):
if self.pk is None: # Adding of a new instance
# let's say we compare instances by `title`
# you can use other fields for the comparison
possible_old_instance = Model.objects.filter(title__iexact=self.title)
if possible_old_instance.exists():
existing_model = possible_old_instance.first()
existing_model.is_deleted = False
existing_model.title = self.title
existing_model.created_at = self.created_at
existing_model.updated_at = self.updated_at
existing_model.created_by = self.created_by
existing_model.deleted_at = None
existing_model.save()
# Nothing happens, we don't call save() method
else:
# in case the Model doesn't exist
super(ModelName, self).save(*args, **kwargs)
else:
super(ModelName, self).save(*args, **kwargs)