I second Eric's opinion, the EntitySingleton is an useful recipy and I used it in SQLAlchemy 5. I think it can be used in your situation well
On Nov 18, 6:51 pm, Eric Ongerth <[EMAIL PROTECTED]> wrote: > Faheem, > > On a closely related note, you may find the following 'usage recipe' > interesting, from the SA wiki. It's from the 0.4 era and I think it's > distinct from your problem (it's addressing attributes as opposed to > primary keys) but still useful and related. > > http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject > > On Nov 18, 8:53 am, Faheem Mitha <[EMAIL PROTECTED]> wrote: > > > On Mon, 17 Nov 2008, Faheem Mitha wrote: > > > Hi, > > > > I've written a session transcript to init db tables and add objects > > > (well, rows) to the tables. The issue I'm currently facing is how to > > > make the "creating and populating the tables" section of the script a > > > no-op when the objects exist. If the tables already exist sqlalchemy > > > does nothing, which is fine. However, this script currently does try to > > > add the objects that are already there, and so throws an exception. I > > > suppose the thing to do would be to check for each object whether it > > > already exists in the db, and do nothing if so. What would be the > > > simplest/cleanest way to do so? I've been fiddling with this for a while > > > without finding an obviously good solution. Is it possible to check > > > whether an "object" is already in a specific table? > > > [following up to my own message] > > > The following approach works, but is kinda kludgy. In particular, I'd like > > to genericise it. The main obstacle in doing so is finding a generic > > expression for the primary key. There is always a primary key, and by > > definition it is unique, right? So, I think it makes sense to use that for > > comparison, but the actual name of the primary key can differ and is can > > also be composite. So, is there a way to access it in a generic way? > > Alternatively, is there a better approach to this? > > > Thanks, Faheem. > > > def add_patient_obj(session, patient_obj): > > """ Check if object primary key exists in db. If so,exit, else add.""" > > pid = patient_obj.id > > if session.query(Patient).filter_by(id=pid).count() > 0: > > print "Patient object with id %s is already in db."%pid > > exit > > else: > > session.save(patient_obj) > > session.commit() --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---