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

FastAPI中如何使用Field别名而非字段名返回Pydantic模型?

问题:FastAPI接口返回数据库模型格式而非指定的Response模型格式

FastAPI接口未返回正确的Response模型格式,而是返回数据库模型格式,代码无报错,仅返回格式不符合预期。

数据库模型代码

class cat(DBConnect.Base):
     __tablename__ = 'category'
     __table_args__ = {"schema": SCHEMA}
     cat_id = Column('cat_id', UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
     cat_desc = Column('cat_desc', TEXT, nullable=True)
     cat_h__l_name = Column('cat_h_l_name', TEXT, nullable=True)

Pydantic模型代码

class CamelModel(BaseModel):
    class config:
        alias_generator = to_camel
        allow_population_by_field_name = True

class cat(CamelModel):
    cat_id = Field(alais='CatID', readonly=True)
    cat_description = Field(alias='CatDescription')
    cat_h__l_name = Field(alias='CatName')
     
    class config:
       orm_mode= True

API接口代码

@router.patch('/cat/{id}/', response_model = 'cat')
def update_cat(response= Response, params: updatecat = Depends(updatecat)):
    response_obj = { resonse_code: status.HTTP_200_OK, 
    response_obj : {}    
    }
    
    response_obj = session.query() # It is returning the correct data from the database
    response.status_code = response_obj['response_code']
    
    return JSONResponse(response_obj['response_obj'], status_code = response_obj['response_code'])

返回格式对比

当前返回格式

cat_id = 'some uuid'
cat_desc = 'desc'
cat_h__l_name = 'some h_l_name'

期望返回格式

CatID = 'some uuid'
CatDescription ='some description'
CatName = 'Some cat name'

解决方案

问题根源

  1. 直接返回JSONResponse绕过转换逻辑:FastAPI的response_model仅在返回ORM对象或Pydantic模型实例时生效,直接返回字典或JSONResponse不会触发模型的别名映射和字段转换。
  2. Pydantic模型存在拼写错误与映射缺失:Field参数alais拼写错误(应为alias);cat_description字段未与数据库的cat_desc关联,无法正确映射值。
  3. response_model引用不规范:response_model='cat'应直接引用类对象而非字符串,避免加载问题。

修复步骤

1. 修正Pydantic模型

from pydantic import BaseModel, Field, UUID4
from pydantic.alias_generators import to_camel

class CamelModel(BaseModel):
    class Config:
        alias_generator = to_camel
        allow_population_by_field_name = True

class cat(CamelModel):
    cat_id: UUID4 = Field(alias='CatID', readonly=True)
    cat_description: str = Field(alias='CatDescription')
    cat_h__l_name: str = Field(alias='CatName')
     
    class Config:
        orm_mode = True
        # 映射数据库字段到Pydantic字段
        fields = {
            "cat_description": "cat_desc",
            "cat_id": "cat_id",
            "cat_h__l_name": "cat_h_l_name"
        }

2. 修改API接口代码

移除JSONResponse,直接返回ORM对象,让FastAPI通过response_model自动处理格式转换:

from fastapi import Response, Depends, status
from sqlalchemy.orm import Session

@router.patch('/cat/{id}/', response_model=cat)
def update_cat(id: UUID4, params: updatecat = Depends(updatecat), response: Response = Response()):
    # 查询目标分类
    db_cat = session.query(cat).filter(cat.cat_id == id).first()
    # 应用更新参数
    for key, value in params.dict(exclude_unset=True).items():
        setattr(db_cat, key, value)
    session.commit()
    session.refresh(db_cat)
    
    response.status_code = status.HTTP_200_OK
    return db_cat

关键说明

  • 开启orm_mode=True(Pydantic v1)或from_attributes=True(Pydantic v2)后,FastAPI可直接将SQLAlchemy ORM对象转换为Pydantic模型实例。
  • 通过fields参数明确数据库与Pydantic字段的映射关系,解决字段名不一致问题。
  • 避免直接返回JSONResponse,确保response_model的转换逻辑生效,输出符合预期的别名格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:55:16