“FastAPI SQLAlchemy 无法将字典更新序列元素 #0 转换为序列”

huangapple go评论111阅读模式
英文:

FastAPI SQLAlchemy cannot convert dictionary update sequence element #0 to a sequence

问题

错误:

  1. ValueError: [TypeError('无法将字典更新序列元素 #0 转换为序列'), TypeError('vars() 参数必须具有 __dict__ 属性')]
英文:

I'm trying to return list of operations and getting error

  1. @router.get("/")
  2. async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)):
  3. query = select(operation).where(operation.c.type == operation_type)
  4. result = await session.execute(query)
  5. return result.all()

Error:

  1. ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]

答案1

得分: 1

尝试使用 result.scalars().all() 而不是 result.all()

英文:

try instead of result.all() to do this result.scalars().all()

答案2

得分: 0

在@matslindh的答案中添加一些细节:

  1. 在你的 schemas.py 中定义响应模型,添加 model_config
  1. class Operation(BaseModel):
  2. model_config: ConfigDict(from_attributes=True)
  3. prop1: type1
  4. prop2: type2
  5. ...

ConfigDict 也要从 pydantic 中导入

  1. 将你的响应模型设置为 List[Operation]
  1. from typing import List
  2. from schemas import Operation
  3. ...
  4. @router.get("/", response_model=List[Operation])

在这种情况下,response.all() 将由 pydantic 处理并转换为序列化响应。

英文:

Adding a bit of details to @matslindh's answer:

  1. in your schemas.py define your response model adding model_config
  1. class Operation(BaseModel):
  2. model_config: ConfigDict(from_attributes=True)
  3. prop1: type1
  4. prop2: type2
  5. ...

ConfigDict is imported from pydantic as well

  1. Set your response model to List[Operation]
  1. from typing import List
  2. from schemas import Operation
  3. ...
  4. @router.get("/", response_model=List[Operation])

In this case response.all() will be processed by pydantic and converted to serialized response

huangapple
  • 本文由 发表于 2023年5月24日 18:05:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定