Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: How to use an instance in SQLAlchemy after session.close()?

Tags:

sqlalchemy

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.

like image 641
fdisk Avatar asked Nov 13 '22 15:11

fdisk


1 Answers

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).

like image 174
EoghanM Avatar answered Dec 22 '22 00:12

EoghanM