根据另一个字段限制字段的值
问题描述:
我需要确保如果模型M中的attribute A
具有某个值,那么attribute B
将不会是None
。根据另一个字段限制字段的值
例如:
M.A == True then M.B != None
M.A = False then M.B = anything (None, int..)
答
您可以使用Model.clean()
:
class M(models.Model):
A = models.BooleanField()
B = models.IntegerField(null=True, blank=True)
def clean(self):
if self.A and self.B is None:
raise ValidationError("B can not be None lwhile A is None")
您将提高ValidationError
在无效的条件。
thx。那解决了它。 – brad