One - One Code All

Blog Content

flask解决SQLAlchemy提示not bound to Session错误的问题session.merge

Python   2016-04-25 18:31:35

在使用 SQLAlchemy 的过程中,有时会出现下列错误:


sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Ba

ckground on this error at: http://sqlalche.me/e/bhk3)


出现以上错误的原因是因为: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 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



上一篇:pandas把dataframe转成Series,改变列中值的类型
下一篇:使用SSL 465端口发送邮件的Python脚本

The minute you think of giving up, think of the reason why you held on so long.