繁体   English   中英

Fastapi Pydantic 可选字段

[英]Fastapi Pydantic optional field

目前,我正在学习 Python 和 Fastapi,但我无法弄清楚打字的用途。可选。

class Post(BaseModel):
    # default value
    rating: int = None
    # typing.Optional
    rating: Optional[int] = None

两者都有效。 我不明白有什么区别。

文档中(参见typing.Optional ):

Optional[x]只是Union[x, None]的简写

在 Pydantic 中,这意味着该字段变为可选的,在初始化 model 时不需要传递任何内容,并且该字段将默认为None (这与 ZC1C425268E68385D14AB5074C17A 中描述的ZC1C425268E68385D14AB5074C179调用中的可选 arguments 略有不同)。

您也不需要明确指定None作为默认值。

在这种情况下,它似乎主要是语法糖,但它有助于使 model 更具可读性。 在更高级的情况下,您可能需要将字段显式传递到 model 中,即使它可能是None ,如Require Optional Fields一节中所建议的那样,在这种情况下,区分就变得必要了。

它始终取决于用例,但您会使用相同类型的默认值或将字段设为必填的情况并不少见。

这是一个更常见的场景:

from pydantic import BaseModel
from typing import Optional

class Post(BaseModel):
    # rating is required and must be an integer.
    rating: int

    # counter is not required and will default to 1 if nothing is passed.
    counter: int = 1

    # comment is optional and will be coerced into a str.
    comment: Optional[str]
# This will work:
post = Post(rating=10)
repr(post)
# 'Post(rating=10, counter=1, comment=None)'

# This will work as well:
post = Post(rating=10, comment="some text")
repr(post)
# "Post(rating=10, counter=1, comment='some text')"

# But this won't work:
post = Post(comment="some text")

# ...
# ValidationError: 1 validation error for Post
# rating
#   field required (type=value_error.missing)

# And this won't work either:
post = Post(rating=10, counter=None)

# ...
# ValidationError: 1 validation error for Post1
# counter
#   none is not an allowed value (type=type_error.none.not_allowed)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM