如何让SQLAlchemy返回Column的comment而非列名作为API响应键?
问题
假设我们通过SQLAlchemy定义如下简单模型:
# Base -> 继承自declarative_base的基类 class Monkey(Base): __tablename__ = "monkey" monkey_id = Column(BIGINT(20), primary_key=True, nullable=False, comment="PowerMonkey")
同时有如下简单的GET API接口(伪代码):
# 伪代码 @app.get("/{monkey_id}") async def get_monkey(): 返回请求中指定ID对应的猴子数据行
能不能让API响应体返回:
{ "PowerMonkey" : 1 }
而不是默认的:
{ "monkey_id" : 1 }
解决方案
完全可以做到,这里提供几种实用的方法:
方法1:手动映射返回字段
这是最直接的方式,查询到数据后手动构造响应字典,把数据库字段名替换成想要的名称:
@app.get("/{monkey_id}") async def get_monkey(monkey_id: int): monkey = db.query(Monkey).filter(Monkey.monkey_id == monkey_id).first() if not monkey: raise HTTPException(status_code=404, detail="猴子不存在") return {"PowerMonkey": monkey.monkey_id}
方法2:用Pydantic模型做字段映射(推荐FastAPI等框架使用)
定义一个Pydantic响应模型,将数据库字段映射到目标响应字段:
from pydantic import BaseModel class MonkeyResponse(BaseModel): PowerMonkey: int class Config: orm_mode = True # 允许直接从ORM模型实例生成响应 @app.get("/{monkey_id}", response_model=MonkeyResponse) async def get_monkey(monkey_id: int): return db.query(Monkey).filter(Monkey.monkey_id == monkey_id).first()
如果字段名完全不匹配,还可以用Field显式指定来源字段:
from pydantic import BaseModel, Field class MonkeyResponse(BaseModel): PowerMonkey: int = Field(..., alias="monkey_id") class Config: orm_mode = True allow_population_by_field_name = True # 允许通过原字段名赋值
方法3:在SQLAlchemy模型中自定义序列化方法
给模型添加一个自定义方法,返回想要的字段结构:
class Monkey(Base): __tablename__ = "monkey" monkey_id = Column(BIGINT(20), primary_key=True, nullable=False, comment="PowerMonkey") def to_response_dict(self): return {"PowerMonkey": self.monkey_id}
然后在接口中调用这个方法返回:
@app.get("/{monkey_id}") async def get_monkey(monkey_id: int): monkey = db.query(Monkey).filter(Monkey.monkey_id == monkey_id).first() if not monkey: raise HTTPException(status_code=404, detail="猴子不存在") return monkey.to_response_dict()
内容的提问来源于stack exchange,提问作者Wonseok Choi
相关产品推荐
相关产品推荐

