Skip to content

Instantly share code, notes, and snippets.

@shuxiang
Last active September 7, 2022 10:34
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

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