我应该如何在 Optional[] 中定义创建子可选模型,使用 FastAPI python 的打字和 pydantic 库?
How shall i define create sub-optional models in Optional[] working with typing and pydantic libs for FastAPI python?
嗨,我是 FastAPI 的初学者,收到这个错误是
TypeError: typing.Union[pydantic.main.stats, NoneType] 不是泛型 class.
如何创建子可选模型?
这些是我的进口商品。
from typing import Optional,List
from pydantic import BaseModel, create_model
您可以只使用可选的嵌套模型,如 doc
中所述
from typing import Optional, Set
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Image(BaseModel):
url: str
name: str
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
tags: Set[str] = []
image: Optional[Image] = None
# do your stuff
嗨,我是 FastAPI 的初学者,收到这个错误是
TypeError: typing.Union[pydantic.main.stats, NoneType] 不是泛型 class.
如何创建子可选模型? 这些是我的进口商品。
from typing import Optional,List
from pydantic import BaseModel, create_model
您可以只使用可选的嵌套模型,如 doc
中所述from typing import Optional, Set
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Image(BaseModel):
url: str
name: str
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
tags: Set[str] = []
image: Optional[Image] = None
# do your stuff