5

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.

fdisk
  • 213
  • 2
  • 7

1 Answers1

1

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

EoghanM
  • 25,161
  • 23
  • 90
  • 123