这是我的简单 Django 类:
class MyClass(models.Model):
my_field1 = models.IntegerField(null=False,blank=False,)
# I want to insert validation rule such that my_field2 = True iff my_field1 > 10
my_field2 = models.BooleanField(null=False, blank=False,)
我想插入验证规则,使得 my_field2
= True iff my_field1
> 10。如果用户输入违反该约束的数据,我希望构造函数引发异常。
#MyClass.object.create(9, False) # Should Succeed
#MyClass.object.create(11, True) # Should Succeed
#MyClass.object.create(31, True) # Should Succeed
#MyClass.object.create(8, True) # Should Throw exception
#MyClass.object.create(21, False) # Should Throw exception
我该怎么做?我读到的有关 django 验证的所有内容都以模型形式出现。但我的申请没有表格。我需要模型本身的验证。我怎样才能做到这一点?
最佳答案
按照答案here 。我认为您正在寻找这样的东西:
from django.db import models
from django.core.validators import MinValueValidator
class MyClass(models.Model):
my_field1 = IntegerField(
validators=[MinValueValidator(11)]
)
关于python - 如何在没有任何形式的情况下验证 Django 模型的构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708596/