Pydantic模式可选

发布于 2025-02-03 16:12:49 字数 354 浏览 3 评论 0原文

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个字符”,

如果我删除'最小长度'约束,它将工作,它将工作按照预期的方式,我可以用一个空字段提交。

我该如何使该字段可选,但是如果填充却有最低值?

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

I specified the variable to be Optional but when I submitted the form without filling in the contact_phone field I am still getting the Error "contact_phone: ensure this value has at least 8 characters"

If I remove 'min-length' constraint, it will work as intended and I can submit with an empty field.

How can I make the field optional but yet have a minimum value if filled?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微暖i 2025-02-10 16:12:49

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

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

You just need to specify a default value:

class PostCreateSchema(BaseModel):
    contact_phone: Optional[constr(strip_whitespace=True, min_length=8,max_length=10)] = None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文