I want to make a function that, given the name of a table, returns the model with that tablename. Eg:
class Model(Base):
__tablename__ = 'table'
...a bunch of Columns
def getModelFromTableName(tablename):
...something magical
so getModelFromTableName('table') should return the Model class.
My aim is to use the function in a simple form generator I'm making since FormAlchemy does not work with python3.2 and I want it to handle foreign keys nicely.
Can anyone give me any pointers on how to get getModelFromTableName to work?
Here's one idea I have (it might be totally wrong, I haven't worked with meta classes before...)
What if I were to make my Model classes inherit from Base as well as some other class (TableReg) and have the class meta of TableReg store Model.tablename in some global dictionary or Singleton.
I realise this could be totally off because Base's metaclass does some very important and totally nifty stuff that I don't want to break, but I assume there has to be a way for me to append a little bit of constructor code to the meta class of my models. Or I don't understand.
I was going to delete this but I figure that the discussion in the comments might be useful for people who want to know about some good practices. Take this answer with a pinch of salt.
something like this does the trick:
if you are working with sqlalchemy automap, you need a slight modification. Took me couple minutes to tune it out:
Utility function for this has been added to SQLAlchemy-Utils. See get_class_by_table docs for more information. The solution in SQLAlchemy-Utils is able to cover single table inheritance scenarios as well.
Beware the OrangeTux answer does not take schemas in account. If you have table homonyms in different schemas use:
fullname
is a Table attribute see: https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/sql/schema.py#L455Inspired by Eevee's comment: