Unbind object from session

Question:

Is it possible to unbind an object from an SQLAlchemy session?

I used to deepcopy it, but as this seems not to be possible when using association proxies I’m searching for another solution to remove the object from a session to add it to another one.

Asked By: Manuel Faux

||

Answers:

Expunge removes an object from the Session, sending persistent instances to the detached state, and pending instances to the transient state:

session.expunge(obj1)

UPDATE: A detached object can be attached to the same or another session by using

session2.add(obj1)

or merged

session2.merge(obj1)

With merge(), the given instance is not placed within the session, and can be associated with a different session or detached. merge() is very useful for taking the state of any kind of object structure without regard for its origins or current session associations and placing that state within a session.

Answered By: Maksym Polshcha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.