Django 更新时如何从模型中触发clean方法?
保存表单时,我会对模型中定义的数据执行验证Django 更新时如何从模型中触发clean方法?,django,django-models,Django,Django Models,保存表单时,我会对模型中定义的数据执行验证 def clean(self): model = self.__class__ if self.unit and (self.is_active == True) and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0: raise
def clean(self):
model = self.__class__
if self.unit and (self.is_active == True) and model.objects.filter(unit=self.unit, is_terminated = False , is_active = True).exclude(id=self.id).count() > 0:
raise ValidationError('Unit has active lease already, Terminate existing one prior to creation of new one or create a not active lease '.format(self.unit))
如何在简单更新期间触发相同的clean方法,而不需要在更新视图中复制clean逻辑?(在我的视图中,我只执行更新,不使用任何形式)
update
不要调用模型的save
方法,因此在这种情况下django不可能引发ValidationError
异常
在进行更新之前,您至少需要调用模型的full\u clean
方法
也许是这样
unit = Unit.objects.get(pk=term.id)
unit.is_active = False
try:
unit.full_clean()
except ValidationError as e:
# Handle the exceptions here
unit.save()
引用:在调用
update
时不可能执行此操作,因为在不加载实例的情况下直接在数据库中执行此操作。
unit = Unit.objects.get(pk=term.id)
unit.is_active = False
try:
unit.full_clean()
except ValidationError as e:
# Handle the exceptions here
unit.save()