SQLAlchemy操作PostgreSQL无法更新字段值问题求助
问题分析与解决
你遇到的问题是SQLAlchemy执行update后返回受影响行数1,但数据库中字段值未更新,核心原因是事务未提交。
解决方案1:手动提交事务
修改你的更新函数,在执行update后调用db.commit()提交事务:
def update_interruption_download_status(db: Session, status: bool, interruption_id: int): affected_rows = (db.query(models.Interruption) .filter(models.Interruption.id == interruption_id) .update({models.Interruption.is_downloaded: status})) db.commit() # 提交事务,将变更同步到数据库 return affected_rows
解决方案2:通过对象实例更新(更直观)
如果更倾向于面向对象的操作方式,可以先查询到对象实例,修改属性后再提交:
def update_interruption_download_status(db: Session, status: bool, interruption_id: int): interruption = db.query(models.Interruption).get(interruption_id) if not interruption: return 0 interruption.is_downloaded = status db.commit() return 1
原因说明
SQLAlchemy的Session默认工作在事务模式下,所有增删改操作都会先在内存中记录,只有调用commit()时才会将这些变更持久化到数据库。你之前的代码只执行了update但未提交事务,当会话结束时事务会自动回滚,因此数据库中看不到任何变化。
额外排查方向
如果提交事务后问题仍存在,可以检查:
- 数据库表是否有触发器,自动覆盖了
is_downloaded字段的更新值; - 数据库用户是否有该表的
UPDATE权限; - 过滤条件
interruption_id是否确实匹配到了目标数据(可以手动执行SQL验证:SELECT * FROM tbl_interruptions WHERE id = [你的ID])。
内容的提问来源于stack exchange,提问作者Mathenge
相关产品推荐
相关产品推荐

