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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM