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

FastAPI中BaseModel与pydantic_model_creator返回方案对比建议

FastAPI中两种API返回序列化方案的对比选择

我是FastAPI初学者,有关于API函数返回内容的疑问。我了解BaseModel可规范API函数的输入参数,在FastAPI中使用Tortoise ORM时,我用pydantic_model_creator函数序列化API返回内容。但最近发现BaseModel也可用于定义API函数的返回内容,示例代码如下:

示例代码

base.py

class UserInfo(BaseModel):
    id : int 
    user_name: str
    age: Optional[int]
    user_type: bool
    nickname: Optional[str]
    user_phone: Optional[str]
    user_email: Optional[str]
    full_name: Optional[str]
    user_status: bool
    header_img: Optional[str]
    sex: int

serializer.py

single_user =  pydantic_model_creator(User, name="single_user", exclude=("password", "remarks", "client_host", "create_time", "update_time",))

function.py

async def user_info(req: Request):
    """
    get current user info
    user_id: int
    """
    user_data = await User.get_or_none(pk=req.state.user_id)
    if not user_data:
        return fail(msg=f"ID{req.state.user_id} is fail!")
    print(user_data.__dict__)
    # return success(msg="user info", data=UserInfo(**user_data.__dict__))
    return await single_user.from_tortoise_orm(user_data) 

两种方案的优劣势对比

手动定义BaseModel(UserInfo)方案

  • 优点:完全自定义返回字段,能精确控制字段类型、可选性,还能添加ORM模型中没有的计算字段;结构直观,其他开发者无需关联ORM模型就能清楚返回内容。
  • 缺点:需手动维护字段,ORM模型字段变更时必须同步修改BaseModel,容易出现遗漏;存在代码冗余,重复定义了ORM中已有的字段。

使用pydantic_model_creator方案

  • 优点:自动从ORM模型生成Pydantic模型,无需重复定义字段;ORM模型字段变更时,只需调整exclude/include参数就能同步序列化模型,维护成本低;支持from_tortoise_orm直接序列化ORM实例,代码更简洁。
  • 缺点:灵活性稍弱,若需添加自定义字段需额外扩展生成的模型;返回结构依赖ORM模型,必须仔细配置exclude/include参数避免泄露敏感信息(如示例中的password)。

总结选择

如果API返回结构和ORM模型高度匹配,仅需排除部分敏感字段,优先选pydantic_model_creator,既省心又能减少维护工作量;如果需要对返回字段做定制化调整(比如重命名、添加计算字段、修改类型),或者不想让API层过度依赖ORM模型,就选择手动定义BaseModel。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:50:22