在使用 SQLAlchemy 的過程中,有時會出現下列錯誤:
- Parent instance '<User at 0x2b45b53509d0>' is not bound to a Session; lazy load operation of attribute cannot proceed
- Instance '<User at 0x2b45b53509d0>' is not bound to a Session; attribute refresh operation cannot proceed
出現以上錯誤的原因是因為:session 已經被提交,導致操作的 model 對象已經不在當前 session 中了。 解決的辦法就是:把對象重新加入到當前 session 中:
def foo(user): # do something... session.commit() user = session.query(User).filter_by(name='Jim').first() foo(user) print user in session # False print user.name # DetachedInstanceError: Instance <User at 0x2b45b53509d0> is not bound to a Session user = session.merge(user) print user in session # True print user.name # Jim session.refresh(user) print user.name # Eric