我有这样的数据库模型
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
不应为空
是否可以对这种情况做条件约束?
您可以在将其保存到数据库之前将方法 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)