Fastapi和Pydantic:如何嵌套对象?



假设我有一个对象"user"还有一个宾语"冠词"。它在Pydantic中定义为(这里是简化版本):

class User(BaseModel):
id: int
name: str
class Config: 
orm_mode = True

class Article(BaseModel):
id: int
text: text
author_id: int
class Config:
orm_mode = True

现在,我想从fastAPI中删除以下内容:

{article: {"id": 1, ""text":"article text", "authorId": 1}, author: {"id":1, "name": "Bob"}}

如何使用pydantic?我是否需要创建一个带有嵌套字典的额外类?还有别的办法吗?怎样才能做到这一点呢?

创建描述所需响应的模式:

class ArticleResponse(BaseModel):
article: Article
author: User

然后将其配置为视图的响应模型,并在视图装饰器中使用response_class=ArticleResponse:

@router.get("/{article_id}", response_class=ArticleResponse)
def ..:
return ArticleResponse(article=article, author=article.author)

最新更新