@classmethod
def get_by_id(cls, id):
user_ = DBSession.query(cls).get(id)
DBSession.close()
return user_
但现在我这样做了
user = User.get_by_id(1)
user.roles
ERROR:Parent instance <User at 0xace51cc> is not bound to a Session;
lazy load operation of attribute 'roles' cannot proceed
那么我怎样才能解决我的问题。非常感谢!
答案 0 :(得分:1)
将用户实例添加到打开的会话中。
# assuming databaseSession is a valid session object using a valid engine
engine = create_engine('mysql://user@localhost:3600/database')
Session = sqlalchemy.orm.sessionmaker()
Session.configure(bind=engine)
databaseSession = Session()
databaseSession.add(user)
user.roles
然后关闭会话。
databaseSession.close()