Skip to content

Instantly share code, notes, and snippets.

@nnnewb
Created February 2, 2019 09:01
Show Gist options
  • Save nnnewb/6c2a89719569301c8fe3098b9d6837b0 to your computer and use it in GitHub Desktop.
Save nnnewb/6c2a89719569301c8fe3098b9d6837b0 to your computer and use it in GitHub Desktop.
discover all sqlalchemy models from _decl_class_registry
from flask_sqlalchemy import SQLAlchemy
def list_models(db: SQLAlchemy):
classes, models, table_names = [], [], []
for clazz in db.Model._decl_class_registry.values():
if getattr(clazz, '__tablename__', None):
table_names.append(clazz.__tablename__)
classes.append(clazz)
for table in db.metadata.tables.items():
if table[0] in table_names:
models.append(classes[table_names.index(table[0])])
return models
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment