假设我有一个 Django 模型:
class MyDjangoModel(models.Model):
name = models.CharField(max_length=200)
attribute = models.IntegerField()
class CustomValidationError(ValidationError):
pass
def clean(self):
if self.attribute < 1:
raise CustomValidationError("Attribute should be > 1!")
if len(self.name) > 20:
raise ValidationError("Name too long!")
我想创建模型实例并验证它:
inst = MyDjangoModel(name="Foo", attribute=0)
try:
inst.full_clean()
except CustomValidationError:
print("Hello!")
except ValidationError:
print("Bye!")
但是上面的代码永远不会打印,"Hello!"因为full_cleanmethod 只引发ValidationError.
任何人都可以建议,如何调用full_clean和检查是否ValidationError引发了子类异常?
相关分类