You need to enable JavaScript to run this app. FastAPI执行PUT更新操作时报500错误:'Test'对象无'items'属性求解
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI执行PUT更新操作时报500错误:'Test'对象无'items'属性求解

问题根因

报错由test.update(request)这行代码触发:
SQLAlchemy查询对象的update()方法要求入参为字典类型的键值对,用来匹配需要更新的字段和对应值,你传入的是Pydantic模型schemas.Test的实例,该实例没有SQLAlchemy要求的items()方法,因此抛出AttributeError。

修复方案

将Pydantic实例转为字典格式后再传入update()方法即可,对应修改路由层代码:

@router.put('/{id}', status_code=status.HTTP_202_ACCEPTED)
def update(id, request:schemas.Test ,db:Session = Depends(get_db)):
    test= db.query(models.Test).filter(models.Test.id == id)
    if not test.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Test with id {id} is not found')
    # Pydantic 1.x 写法
    test.update(request.dict())
    # 若使用Pydantic 2.x 请替换为下面的写法
    # test.update(request.model_dump())
    db.commit()
    return 'updated'

如果需要只更新用户实际传入的字段、避免覆盖未传字段为默认值,可以在转字典时添加参数:

  • Pydantic 1.x: request.dict(exclude_unset=True)
  • Pydantic 2.x: request.model_dump(exclude_unset=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 05:36:04