Querying specific class using String name of class

14 views
Skip to first unread message

JPLaverdure

unread,
Aug 22, 2011, 3:08:59 PM8/22/11
to sqlal...@googlegroups.com
Hello,

Is there a proper way to retrieve a class using its name other than going through the _decl_class_registry dictionary of declarative_base ?
I'm using the Joined Table Inheritance and would like to enable users to query specific subtypes.

ie: if I have the following structure:
Base  = declarative_base()

class Sample(Base):
  bla

class Tissue(Sample):
  bla

class DNA(Sample):
  bla

I would like to build a query using 'DNA' as class type...
session.query('DNA').all()

But this doesn't work so the solution I found is the following:
session.query(Base._decl_class_registry['DNA'])

Is this the only way to go or is there a cleaner way to obtain a class based on its String name ?

Thanks !


Mike Gilligan

unread,
Aug 23, 2011, 10:29:57 AM8/23/11
to sqlalchemy
`eval` should work. Something like this:

session.query(eval('DNA')).all()

JPLaverdure

unread,
Aug 23, 2011, 11:12:29 AM8/23/11
to sqlal...@googlegroups.com
Hi Mike,

Thanks for the reply. 
I'm just not sure that using `eval` represents a "cleaner" way than my original code...

The Class query options are specified by the end user through a <select> (html form) so using eval poses a security risk I would like to avoid.

I was hoping slqalchemy would give me a clean way to access mapped objects using a String as Identifier. Like a getter of some kind.

JP

  
 
Reply all
Reply to author
Forward
0 new messages