I am having problems using an instance in SQLAlchemy after session.close().
This is the code:
session = sqlalchemy.orm.sessionmaker(bind=engine)
object = session.query(Entity).filter(Entity.id == id).one()
object.name = "Foo"
session.commit()
session.close()
print object.name
It throws a DetachedInstanceError.
I have tried to detach the object, expunge_all() and nothing.
Thanks
Edit
I found out what was the problem. For future reference I will answer my own question.
session.commit() sets the object instance as expired, when I try to access to the object attributes after the close() statement SQLAlchemy tries to refresh the instance. Calling refresh after commit() solves the problem.
You could also try the setting expire_on_commit=False
which affects the commit
call and may mean you don't need to do the refresh
(assuming that's costly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With