SQLAlchemy报错:sqlalchemy.orm.exc.DetachedInstanceError

使用SQLAlchemy时报错: sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x809ab1f> is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3) 解决方案: 在初始化数据库的代码中,将 maker = sessionmaker(bind=eng) 修改为 maker = sessionmaker(bind=eng, expire_on_commit=False) 为什么要添加 expire_on_commit=False 参数? expire_on_commit 可以用来更改 SQLAlchemy 的对象刷新机制,默认值为 True ,即在 session 调用 commit 之后会主动将同一个session在commit之前查询得到的ORM对象的_sa_instance_state.expire属性设置为Flase,再次读取该对象属性时将重载这个对象,方法是重新调用之前的查询语句。 参考: https://www.dazhuanlan.com/2019/12/23/5e004dedbc72d/#expire_on_commit https://cloud.tencent.com/developer/ask/219084
我的笔记
你可能想看的