15 messages in com.googlegroups.sqlalchemy[sqlalchemy] Re: Is there a way to re...| From | Sent On | Attachments |
|---|---|---|
| Denis S. Otkidach | 26 Dec 2007 09:12 | |
| Michael Bayer | 26 Dec 2007 11:38 | |
| Denis S. Otkidach | 27 Dec 2007 01:11 | |
| Michael Bayer | 27 Dec 2007 13:58 | |
| Rick Morrison | 27 Dec 2007 13:59 | |
| braydon fuller | 27 Dec 2007 15:01 | |
| Rick Morrison | 27 Dec 2007 15:06 | |
| Denis S. Otkidach | 28 Dec 2007 02:49 | |
| Michael Bayer | 28 Dec 2007 07:25 | |
| Denis S. Otkidach | 11 Jan 2008 09:30 | |
| Michael Bayer | 11 Jan 2008 09:41 | |
| Denis S. Otkidach | 15 Jan 2008 05:20 | |
| Michael Bayer | 15 Jan 2008 07:54 | |
| Denis S. Otkidach | 16 Jan 2008 01:43 | |
| Michael Bayer | 16 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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to sqla...@googlegroups.com
To unsubscribe from this group, send email to
sqla...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---




