根据另一个字段限制字段的值

问题描述:

我需要确保如果模型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在无效的条件。

+0

thx。那解决了它。 – brad