pydantic schema Optional


from Typing import Optional

class PostCreateSchema(BaseModel):

contact_phone:Optional[constr(strip_whitespace=True, min_length=8,max_length=10)]

我指定变量为可选,但当我提交表单时没有填写contact_phone字段,我仍然得到错误"contact_phone:确保这个值至少有8个字符">

如果我删除'min-length'约束,它将按预期工作,我可以提交一个空字段。

如何使字段可选,但有一个最小值,如果填充?

您只需要指定一个默认值:

class PostCreateSchema(BaseModel):
contact_phone: Optional[constr(strip_whitespace=True, min_length=8,max_length=10)] = None

最新更新