Thursday 21 October 2021

SQLAlchemy with multiple session, how to avoid "Object is already attached to session X"?

I have a special configuration where I've created two SQLAlchemy Sessions from the sessionmaker :

db.read = sessionmaker(autoflush=False)
db.write = sessionmaker()

When calling db.write.add(obj), I sometimes have the following error (but not always):

sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7f3fa9ebee50>' is already attached to session '14' (this is '15')

Is there a way to do the following :

"If session is db.write, then call db.write.add(obj) Otherwise, add obj to the db.write session in order to save it, and (important), update both the object in db.write session AND db.read session"

(I've managed to save to via write, but then, obj.id is empty in db.read)

Thank you for your help



from SQLAlchemy with multiple session, how to avoid "Object is already attached to session X"?

No comments:

Post a Comment