sqlalchemy错误:sqlalchemy.orm.exc.DetachedInstanceError

使用sqlchemy报错。

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)

解决方案:
将原
sessionmaker(bind=eng)
修改为
sessionmaker(bind=eng, expire_on_commit=False)

关于expire_on_commit:

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

原文地址:https://www.cnblogs.com/ice5/p/14258774.html