you can also use 'try' to avoid error messages: def ensure_object(db, id): try: o = db.Query(ModelObject).get(id) except: o = ModelObject(1, u'title') db.save(o) db.commit() return o
-Braydon Rick Morrison wrote: > > ...if you're just checking to see if something exists in the database, > why not just try to .load() it, and then construct it afresh if you > don't find it? > > This kind of operation is sometimes called an "upsert" ...some > database engines support it, some don't. Most don't. But what all > database engines DO support is a query, followed by either an insert, > or an update as appropriate. > > Here's the idiom that should work: > > def ensure_object(sess, id): > o = sess.Query(ModelObject).get(id) # if found, o is now loaded > into session > if not o: > o = ModelObject(1, u'title' > sess.save(o) > sess.flush() > return o > --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en -~----------~----~----~----~------~----~------~--~---