Skip to content

Instantly share code, notes, and snippets.

@shuxiang
Last active August 7, 2025 08:19
Show Gist options
  • Save shuxiang/c12be33cdcd9a86f20a2 to your computer and use it in GitHub Desktop.
Save shuxiang/c12be33cdcd9a86f20a2 to your computer and use it in GitHub Desktop.
sqlalchemy get model by name and get model by tablename
from flask.ext.sqlalchemy import SQLAlchemy
def get_model(self, name):
return self.Model._decl_class_registry.get(name, None)
SQLAlchemy.get_model = get_model
def get_model_by_tablename(self, tablename):
for c in self.Model._decl_class_registry.values():
if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
return c
SQLAlchemy.get_model_by_tablename = get_model_by_tablename
db = SQLAlchemy(app)
@netanelbarel
Copy link

My _decl_class_registry is empty

@umayrh
Copy link

umayrh commented Aug 7, 2025

Here's an alternative:

default_registry = registry()
Model = default_registry.generate_base()
...
def get_model_by_tablename(self, tablename):
    for model_clz in default_registry._class_registry.values():
        if (hasattr(model_clz, '__tablename__') and
                model_clz.__tablename__ in matching_table_names):
            return model_clz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment