解決 SQLAlchemy 提示 Instance is not bound to a Session 錯誤的問題


在使用 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM