SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see python python

SQLAlchemy: get Model from table name. This may imply appending some function to a metaclass constructor as far as I can see


Inspired by Eevee's comment:

def get_class_by_tablename(tablename):  """Return class reference mapped to table.  :param tablename: String with name of table.  :return: Class reference or None.  """  for c in Base._decl_class_registry.values():    if hasattr(c, '__tablename__') and c.__tablename__ == tablename:      return c


Beware the OrangeTux answer does not take schemas in account. If you have table homonyms in different schemas use:

def get_class_by_tablename(table_fullname):  """Return class reference mapped to table.  :param table_fullname: String with fullname of table.  :return: Class reference or None.  """  for c in Base._decl_class_registry.values():    if hasattr(c, '__table__') and c.__table__.fullname == table_fullname:      return c

fullname is a Table attribute see:

github.com/sqlalchemy/sqlalchemy/blob/master/lib/sqlalchemy/sql/schema.py#L530-L532


So in SQLAlchemy version 1.4.x (which I updated to around 2020-03-16) it seems _decl_class_registry no longer exists.

I was able to work around using the new registry class attribute (which is not protected, so hopefully it wont be removed suddenly!).

Base.TBLNAME_TO_CLASS = {}for mapper in Base.registry.mappers:    cls = mapper.class_    classname = cls.__name__    if not classname.startswith('_'):        tblname = cls.__tablename__        Base.TBLNAME_TO_CLASS[tblname] = cls

Not sure if this is the best way to do it, but its how I did it.