根据另一个限制字段的值

时间:2015-07-28 06:47:23

标签: django django-models

我需要确保如果模型M中的attribute A具有特定值,则attribute B将不会是None

例如:

M.A == True then M.B != None

M.A = False then M.B = anything (None, int..)

1 个答案:

答案 0 :(得分:1)

您可以使用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