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

FastAPI使用ORM返回数据报错,寻求无需scalars()的解决方案

FastAPI ORM 返回数据无需scalars()的解决方案

问题现象

使用FastAPI + SQLAlchemy ORM返回数据时触发以下报错,不想使用scalars()方法:

pydantic.error_wrappers.ValidationError: 1 validation error for BaseOperation response
value is not a valid list (type=type_error.list)

现有代码

schemas.py

from typing import Optional, List
from datetime import datetime
from pydantic import BaseModel

class Operation(BaseModel):
    id: int
    quantity: str
    figi: str
    instrument_type: str
    type: str
    date: datetime

class OperationCreate(BaseModel):
    id: int
    quantity: str
    figi: str
    instrument_type: str
    date: datetime
    type: str

class BaseOperation(BaseModel):
    data: Optional[List[Operation]]
    class Config:
        orm_mode = True

router.py(报错版本)

@router.get("/",response_model=List[BaseOperation])
async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)):
    query = select(operation).where(operation.c.type == operation_type)
    result = await session.execute(query)
    return {
        "data": result.all()
    }

问题根源

  1. Response Model不匹配:设置的response_model=List[BaseOperation]期望返回BaseOperation对象的列表,但实际返回的是包含data键的单个字典,结构完全不符。
  2. Row对象解析:result.all()返回SQLAlchemy的Row命名元组集合,不过Pydantic的orm_mode=True支持通过属性访问解析这类对象,只要字段名完全匹配即可。

解决方案

修改router.py中的response_model为BaseOperation,直接返回{"data": result.all()}即可,无需额外转换:

@router.get("/", response_model=BaseOperation)
async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)):
    query = select(operation).where(operation.c.type == operation_type)
    result = await session.execute(query)
    return {"data": result.all()}

说明

  • 调整response_model后,返回的字典结构和BaseOperation模型完全对应,Pydantic会自动解析Row对象为Operation模型实例。
  • 无需使用scalars()或手动转字典,直接利用Pydantic的orm_mode特性即可完成解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:52:48