Created
February 2, 2019 09:01
-
-
Save nnnewb/6c2a89719569301c8fe3098b9d6837b0 to your computer and use it in GitHub Desktop.
discover all sqlalchemy models from _decl_class_registry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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