You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何让带泛型的自定义Pydantic类自动生成Swagger示例?

解决Pydantic v2泛型类自动生成CoreSchema及Swagger示例问题

要让Other[Member]的示例像member字段一样自动从Member模型生成,你需要修改Other类的__get_pydantic_core_schema__方法,复用传入的泛型参数的CoreSchema,而非手动定义字段。

修改后的完整代码

import uvicorn

from pydantic import BaseModel, GetCoreSchemaHandler
from pydantic_core import CoreSchema, core_schema
from fastapi import FastAPI
from typing import TypeVar, Generic, get_args

T = TypeVar("T")


class Other(Generic[T]):
    @classmethod
    def __get_pydantic_core_schema__(
        cls, __source: type[BaseModel], __handler: GetCoreSchemaHandler
    ) -> CoreSchema:
        # 获取泛型参数对应的模型类
        member_model = get_args(__source)[0]
        # 让handler处理该模型,生成对应的CoreSchema
        return __handler(member_model)


class Member(BaseModel):
    first_name: str
    last_name: str | None = None
    age: int


class House(BaseModel):
    member: Member
    other_member: Other[Member]


app = FastAPI()


@app.post("/houses/", response_model=House)
async def create_house(house: House):
    return house


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

关键修改说明

  • 去掉了手动构建typed_dict_schema的代码,转而调用__handler(member_model),让Pydantic自动处理传入的泛型模型,生成对应的CoreSchema。
  • 这样Other[Member]会完全复用Member的结构和元数据(包括示例值),Swagger UI中other_member字段的示例会和member字段一致,无需手动指定。

额外说明

如果Other需要对泛型模型做额外包装(比如添加固定字段),可以在返回的CoreSchema中组合原模型的schema,示例如下:

@classmethod
def __get_pydantic_core_schema__(
    cls, __source: type[BaseModel], __handler: GetCoreSchemaHandler
) -> CoreSchema:
    member_model = get_args(__source)[0]
    member_schema = __handler(member_model)
    # 添加额外字段并组合原模型的字段
    return core_schema.typed_dict_schema(
        {
            **member_schema["fields"],
            "extra_field": core_schema.typed_dict_field(core_schema.int_schema())
        }
    )

内容的提问来源于stack exchange,提问作者suraw00t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:36:09