[英]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.