django 模型的条件约束

问题描述 投票:0回答:1

我有这样的数据库模型

ActionType = (
    (1,"PostBack"),
    (2,"Uri"),
)

class RichMenu(BaseModel):
    key = m.CharField(max_length=64,unique=True)
    action_type = m.IntegerField(choices=ActionType,default=1)
    url = m.CharField(max_length=255,blank=True,null=True)
    name = m.CharField(max_length=255,blank=True,null=True)

现在我想做出这样的约束,

  • action_type
    为1时,
    url
    应为空,
    name
    不应为空

  • action_type
    为2时,
    name
    应为空,
    url
    不应为空

是否可以对这种情况做条件约束?

python django model
1个回答
0
投票

您可以在将其保存到数据库之前将方法 save() 覆盖到有效字段

ActionType = (
    (1,"PostBack"),
    (2,"Uri"),
)

class RichMenu(BaseModel):
    key = m.CharField(max_length=64,unique=True)
    action_type = m.IntegerField(choices=ActionType,default=1)
    url = m.CharField(max_length=255,blank=True,null=True)
    name = m.CharField(max_length=255,blank=True,null=True)

    def save(self, *args, **kwargs):
        if self.action_type == 1:
            if self.url is not None and self.name is None:
                raise Exception("INVALID URL AND NAME")
        elif self.action_type == 2:
            if self.url is None and self.name is not None:
                raise Exception("INVALID URL AND NAME")
        super(RichMenu, self).save(*args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.