FastAPI与SQLAlchemy报错:无法将字典更新序列元素#0转换为序列
问题:返回操作列表时触发ValueError错误
代码示例
@router.get("/") 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 result.all()
错误信息
ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]
错误原因
你直接返回了SQLAlchemy执行查询后得到的Row对象列表。FastAPI默认的JSON序列化器无法处理这类对象——Row实例没有__dict__属性,序列化时调用vars()就会触发报错,同时字典转换逻辑也会失败。
解决方案
有两种简单的修复方式:
方法1:使用mappings()返回字典列表
SQLAlchemy的Result对象提供了mappings()方法,直接返回可被FastAPI序列化的字典列表:
@router.get("/") 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 result.mappings().all()
方法2:将Row对象转为字典
遍历result.all()得到的Row实例,调用_asdict()方法转为字典:
@router.get("/") 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 [row._asdict() for row in result.all()]
两种方法都能解决序列化问题,推荐使用方法1,代码更简洁且性能更优。
内容的提问来源于stack exchange,提问作者Nazar Shpargal
相关产品推荐
相关产品推荐

