I am facing some odd problems while learning SQLAlchemy. I am using 0.7.2 version of it. These are my test classes:
class User(Base):
__tablename__ = 'users'
id = Column('user_id',Integer,primary_key = True)
name = Column('user_name',String(20))
addresses = relationship("Address",backref="user")
def __repr__(self):
return "<User(%s)>" % self.name
class Address(Base):
__tablename__ = 'addresses'
id = Column('adress_id',Integer,primary_key = True)
address = Column('address',String(30))
user_id = Column('user_id',ForeignKey('users.user_id'))
def __repr__(self):
return "<Address(%s)>" % self.address
-
I accidentally ran my main file twice which made following code run twice
Session = sessionmaker() session = Session(bind=engine) q=session.query(User) a=q.get(3) a.addresses.append(Address(address='myaddress')) session.flush() print a.addresses[0].id,a.addresses[0].addressI initially thought that a.addresses would have got two address object with ‘myaddress’. But actually there is only one object whose address_id got updated. I mean to say when I ran file first it printed
1,'myaddress' and then in second run it printed 2,'myaddress'
I confirmed existence of only Address object by printing a.addresses and it shows only object in it.
Should it not add a second Address object in a.addresses on append instead of updating id of existing address object?
Note there is no session.commit() command executed. I simply ran the file twice and noticed this behaviour.
Edit : Added code which creates new session and is responsible for the problem as suggested by van below in the answer
This cannot be seen in your code, but I assume that the code that is executed twice is also executed within two different sessions. This would explain all the side effects you observe:
IDis increased: this happens because offlush()in the first session where the identifier is assigned to the object. This is not an update to the previousAddressthough, but rather anIDassignment to the newAddress.