1 from sqlalchemy import * 2 from sqlalchemy.orm import * 3 4 metadata = MetaData() 5 6 t = Table( 7 't', metadata, 8 Column('id', Integer, primary_key=True), 9 Column('state', String(10)), 10 ) 11 12 class Model(object): pass 13 14 mapper(Model, t) 15 16 engine = create_engine('sqlite://') 17 metadata.create_all(engine) 18 19 session = sessionmaker(bind=engine)() 20 21 obj1 = Model() 22 obj1.state = 'value1' 23 session.add(obj1) 24 session.commit() 25 obj_id = obj1.id 26 27 obj2 = Model() 28 obj2.id = obj_id 29 obj2.state = 'value2' 30 obj3 = session.merge(obj2) 31 session.commit() 32 print obj3 is obj1, obj3 is obj2 33 print obj3.state
结果:
True False
value2
1 from sqlalchemy import * 2 from sqlalchemy.orm import * 3 4 metadata = MetaData() 5 6 t = Table( 7 't', metadata, 8 Column('id', Integer, primary_key=True), 9 Column('state1', String(10)), 10 Column('state2', String(10)), 11 ) 12 13 class Model(object): pass 14 15 mapper(Model, t) 16 17 engine = create_engine('sqlite://') 18 metadata.create_all(engine) 19 20 session = sessionmaker(bind=engine)() 21 22 obj1 = Model() 23 obj1.state1 = 'value1-1' 24 obj1.state2 = 'value2-1' 25 session.add(obj1) 26 session.commit() 27 obj_id = obj1.id 28 session.expunge_all() 29 30 obj2 = Model() 31 obj2.id = obj_id 32 obj2.state1 = 'value1-2' 33 obj3 = session.merge(obj2) 34 session.commit() 35 print obj3 is obj1, obj3 is obj2 36 print obj3.state1, obj3.state2
结果:
False False
value1-2 value2-1