FastAPI中返回多Pydantic模型列表的响应模型配置问题
解决方案:FastAPI 返回多类型模型列表的正确配置
你的问题核心在于单个模型使用了__root__包裹Union类型,但列表场景下不需要额外包裹,直接使用带鉴别器的Union列表即可。以下是两种可行方案:
方案一:直接在接口中指定响应模型
无需额外创建列表模型,直接将response_model设为List[Union[ResponseHouseSeekerPosting, ResponseHouseSharerPosting]],配合参数完成验证:
from typing import List, Union from fastapi import APIRouter router = APIRouter() @router.get( path='/posts', response_description="Retrieves a list of postings of the user", status_code=200, response_model=List[Union[ResponseHouseSeekerPosting, ResponseHouseSharerPosting]], response_model_by_alias=False ) async def get_user_posts(post_type: PostingType): user = users_db_connection.aggregate("Some Aggregate Query that returns the list of posts for the user, this works properly") async for doc in user: return doc['postings']
关键说明:
- 模型中通过
Literal固定的postingType字段会自动作为鉴别器,FastAPI会根据该字段值匹配对应的子模型 response_model_by_alias=False确保使用模型原始字段名验证,避免别名冲突
方案二:创建专门的列表响应模型
若需独立模型管理列表结构,可定义包含带鉴别器Union列表的模型:
from typing import List, Union from pydantic import BaseModel, Field class ResponseGetPostList(BaseModel): __root__: List[Union[ResponseHouseSeekerPosting, ResponseHouseSharerPosting]] = Field( ..., discriminator='postingType' )
接口中指定该模型并按结构返回数据:
@router.get( path='/posts', response_description="Retrieves a list of postings of the user", status_code=200, response_model=ResponseGetPostList ) async def get_user_posts(post_type: PostingType): user = users_db_connection.aggregate("Some Aggregate Query that returns the list of posts for the user, this works properly") async for doc in user: return {"__root__": doc['postings']}
之前尝试失败的原因
你使用List[ResponseGetPost]时,每个列表元素被要求符合ResponseGetPost的结构——即必须包裹在__root__字段中,但数据库返回的是直接的Posting对象列表,没有外层__root__,因此触发验证错误。
补充校验要点
确保数据库返回的doc['postings']中,每个元素的postingType字段值严格匹配PostingType枚举的字符串值('House Seeker'或'House Sharer'),否则鉴别器无法正确识别模型类型。
内容的提问来源于stack exchange,提问作者Ahmet-Salman
相关产品推荐
相关产品推荐

