英文:
FastAPI SQLAlchemy cannot convert dictionary update sequence element #0 to a sequence
问题
错误:
ValueError: [TypeError('无法将字典更新序列元素 #0 转换为序列'), TypeError('vars() 参数必须具有 __dict__ 属性')]
英文:
I'm trying to return list of operations and getting error
@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()
Error:
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的答案中添加一些细节:
- 在你的
schemas.py
中定义响应模型,添加model_config
class Operation(BaseModel):
model_config: ConfigDict(from_attributes=True)
prop1: type1
prop2: type2
...
ConfigDict
也要从 pydantic
中导入
- 将你的响应模型设置为
List[Operation]
from typing import List
from schemas import Operation
...
@router.get("/", response_model=List[Operation])
在这种情况下,response.all()
将由 pydantic
处理并转换为序列化响应。
英文:
Adding a bit of details to @matslindh's answer:
- in your
schemas.py
define your response model addingmodel_config
class Operation(BaseModel):
model_config: ConfigDict(from_attributes=True)
prop1: type1
prop2: type2
...
ConfigDict
is imported from pydantic
as well
- Set your response model to
List[Operation]
from typing import List
from schemas import Operation
...
@router.get("/", response_model=List[Operation])
In this case response.all()
will be processed by pydantic
and converted to serialized response
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论