15 messages in com.googlegroups.sqlalchemy[sqlalchemy] Re: Is there a way to re...
FromSent OnAttachments
Denis S. Otkidach26 Dec 2007 09:12 
Michael Bayer26 Dec 2007 11:38 
Denis S. Otkidach27 Dec 2007 01:11 
Michael Bayer27 Dec 2007 13:58 
Rick Morrison27 Dec 2007 13:59 
braydon fuller27 Dec 2007 15:01 
Rick Morrison27 Dec 2007 15:06 
Denis S. Otkidach28 Dec 2007 02:49 
Michael Bayer28 Dec 2007 07:25 
Denis S. Otkidach11 Jan 2008 09:30 
Michael Bayer11 Jan 2008 09:41 
Denis S. Otkidach15 Jan 2008 05:20 
Michael Bayer15 Jan 2008 07:54 
Denis S. Otkidach16 Jan 2008 01:43 
Michael Bayer16 Jan 2008 08:41 
Subject:[sqlalchemy] Re: Is there a way to replace object in DB?
From:braydon fuller (cour@braydon.com)
Date:12/27/2007 03:01:06 PM
List:com.googlegroups.sqlalchemy

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