my approach to this is to fetch all objects that look like my objects and then add the ones that are missing. e.g. q = query(A).filter( A.name.in_( allnames_that_should_be) ) missingnames = set( allnames_that_should_be) - set( a.name for a in q) for name in missingnames: ... probably would be even faster if u use q = query(A.name).filter(...) directly
at least this gives one query as opposed to hundreds query.filter_by( some_user_primary_key) - but it depends on the situation, numbers and filtering criterias. Note the "some_user_primary_key" above: checking if dbid=5 exists is meaningless - any 5th object will have it; u have to check by meaningfull "user" or "application-field" "primary" keys. also, the in_() operator does not scale well (YMMV), so u may have to slice into portions if the list is way too big. ciao svilen > > > 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 [email protected] 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 -~----------~----~----~----~------~----~------~--~---
