Dunno, let's try it:
import sqlalchemy as sa
import sqlalchemy.orm as saorm
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Person(Base):
__tablename__ = 'people'
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
name = sa.Column(sa.String(20))
if __name__ == '__main__':
engine = sa.create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = saorm.sessionmaker(bind=engine)
# Create our first session and use it to add a Person to the database
sess1 = Session()
sess1.add(Person(name='lars'))
sess1.commit()
sess1.close()
# Retrieve our Person from the database again.
person = sess1.query(Person).first()
# Now try to add that instance to a second session
sess2 = Session()
sess2.add(person)
sess2.commit()
Output:
Traceback (most recent call last):
...
sqlalchemy.exc.InvalidRequestError: Object '<Person at 0x10c9f5790>' is already attached to session '1' (this is '2')
Looks very similar to your error message. I'm using SA 0.8.0 - it looks like the message is slightly different in your version.
The correct thing to do in this case is to use "session.merge" to create a copy of the object, attached to the new session. If you change the last few lines of the script above to:
sess2 = Session()
merged = sess2.merge(person)
sess2.add(merged)
...it works fine.
Hope that helps,
Simon