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

Leave a Comment