On Oct 18, 2011, at 1:21 PM, Manav Goel wrote: > Hello, > I am working in eclipse IDE. > I have this code in the file : > > > class User(Base): > __tablename__ = 'users' > > id = Column('user_id',Integer,primary_key = True) > name = Column('user_name',String(20)) > > addresses = relationship("Address") > > def __repr__(self): > return "<User(%s)>" % self.name > > session = Session(bind=engine) > u=User('myname') > session.add(u) > session.flush() > print u.id > > I ran this file and it worked fine but then I changed > something. > Now to see the effect I have to run file again and then I > noticed this > > Instead of adding two different objects with two > different ids but same name. It simply updated the id of already existing > object. > > Now I have two questions : > > 1. What is the reason of this behavior? First of all it should have > made two different objects .
absolutely. the User() object has no primary key assigned and is not the result of a previous query, so add() will add it as a new row. So the code above is not the complete story and you'd have to figure out what you're doing on your end beyond what's illustrated above. > But I think it did not do that because it thought this object is similar to > existing one. This is not SQLA's behavior. SQLAlchemy does not make guesses about data. > In that case it should have raised exception instead of simply my primary key. what kind of exception ? its legal to have two objects with the same name here unless you applied a unique constraint to the "user_name" column which does not seem to be the case here. > > 2. WHat happened when I ran the file again? It created a brand new > session or continued the previous one? The Session is an instantiation of an object present in memory only within the Python process. So by definition any new invocation of a Python program begins with all new state including Session objects. > > 3. Due to problem mentioned in point no 1. it wasted my early id nos > as when I committed it saved the last one? I don't know what this means. -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.