David S.
David S.

Reputation: 11148

How to use a Sqlalchemy Model out of a session context?

In Sqlalchemy, a model instance is constantly connected to a session. If the session is ended, I won't be able to read the object. But in many cases, I want to close the session early to return resources, meanwhile still using the model instance.

Currently, I am reading all the values out and put them into a dict. But I am looking for a easier and automatic way.

Upvotes: 2

Views: 2876

Answers (2)

parkouss
parkouss

Reputation: 606

In Sqlalchemy, a model instance is NOT constantly connected to a session. The session is here to make the link between your objects and the database (http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#what-does-the-session-do)

This means that you can act on your objects without session at all. Still their states will be reflected on your DB only when you will ask for it, EG by using a session.

session = Session()
# get some objects
objects = session.query(MyObject).all()
# then close the session
session.close()

# later on (on another function or whatever) you can manipulate your objects
objects[0].attr = 'myvalue'
objects[1].attr2 = 42

# and once you are done finally commit (this can also be done wherever you want to).
session = Session()
session.add_all(objects)
session.commit()

Upvotes: 2

maralla
maralla

Reputation: 2741

You can configure sessionmaker with expire_on_commit = False

Session = sessionmaker(expire_on_commit=False)

Upvotes: 2

Related Questions