On Sun, Jan 11, 2009 at 5:58 AM, drakkan <[email protected]> wrote: > > Hi, > > I'm new to tg and sqlalchemy, I worte my simple sa model with some > integrity costraint such as unique=True > > If i create a new database object for example > > obj=DBObject(name='test',other='other') > > and then save > > DBSession.add(obj) > > the first time all works fine, if I create the same object and try to > save the unique costraint is violated and my controller return a 500 > error, obviously I try to use: > > try: > DBSession.add(obj) > except: > pass > > but nothing a TypeError: Already committed is raised, > This is wrong, when you instantiate and object for the first time you call add on it which will get you that object, if you want "the same object" you need to query for it, NOT create a new instance, this will break the contraint (you have two objects with the same "unique" value), this error will only show when the query hits the db.
> I need to make a query before saving to check if the unique costraint > is violated? In my opinion a best solution is a way to trap the > dberror and show an error message to the users > no you need to "flush to the db" in tg2 this is done by issuing transaction.commit(), which together with other things calls DBSession.flush() > another question: > > if I use paster shell I have to issue transaction.commit() to make > database change, in tg2 controller seems that transaction.commit is > automatically called so is enough a DBSession.add(obj) is this > correct? > This depends, your current session is flushed if SA needs to go to the db, for example if you do add, then query, the add will "commit" as it needs to have "fresh data" in order for the query to work. Read up on the "unit of work" pattern if you want to understand this fully. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "TurboGears" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/turbogears?hl=en -~----------~----~----~----~------~----~------~--~---

