def add_obj(session, obj):
     """ Check if object primary key exists in db. If so,exit, else
     add.
     """
     pid = obj.id
    if session.query(obj.__class__).filter_by(id=pid).count():
         print "Patient object with id %s is already in db."%pid
         exit
     else:
         session.save(obj)
         session.commit()


Not too difficult.  You can also use type(obj) instead of
obj.__class__.

Furthermore, if you really need to determine the object's class's
mapped table,
obj_table = obj.__class__._sa_class_manager.mapper.mapped_table

Of course, being an underscored thing, _sa_class_manager is not
something you should count on from version to version of sqlalchemy,
so keep that in consideration and don't use it anywhere you don't plan
to maintain.

Eric


On Dec 2, 2:24 pm, Faheem Mitha <[EMAIL PROTECTED]> wrote:
> Hi,
>
> If I have an ORM object, it is sometimes convenient to be able to infer
> the class directly. Eg. consider this function.
>
> def add_patient_obj(session, patient_obj):
>      """ Check if object primary key exists in db. If so,exit, else
>      add."""
>      pid = patient_obj.id
>      #print session.query(Patient).filter_by(id=pid).count()
>      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()
>
> But I want a generic version. Since patient_obj knows what class is
> belongs to, it should be possible not to have to state the class directly,
> which here is Patient.
>
> I have done the following, which works, but is hideous, horrible, ugly,
> fragile hack. Can anyone suggest a better way of doing this?
>
> Please CC me on any reply. Thanks in advance.
>
>                                                     Regards, Faheem.
>
> def add_obj(session, obj):
>      """ Check if object primary key exists in db. If so,exit, else
>      add.
>      """
>      c = str(type(obj)).split("'")[1].split(".")[1]
>      s = "q = session.query("+ c +")"
>      exec(s)
>      pid = obj.id
>      if q.filter_by(id=pid).count() > 0:
>          print "Patient object with id %s is already in db."%pid
>          exit
>      else:
>          session.save(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
-~----------~----~----~----~------~----~------~--~---

Reply via email to