Search code examples
flasksqlalchemyflask-sqlalchemy

Get all models from flask-sqlalchemy db


After a database is constructed in SQLAlchemy, I want to get all of the models, which is to say, the classes which represent them

>>> db
<SQLAlchemy engine='postgresql:///example'>
>>> ???
[<db.Model 'User'>, <db.Model 'Comment'>, <db.Model 'Article'>]

Can this be achieved? How?

I can get the tables decently, just not the models. Eg:

>>> for t in db.metadata.tables.items():
        print(t)

this gives the tables just not the models themselves


Solution

  • There are several related questions, but I didn't see any exact duplicates.

    Using your code to get the table names, and this question's accepted answer to get the classes, we can match the classes to the tablenames that are registered on your database.

    classes, models, table_names = [], [], []
    for clazz in db.Model._decl_class_registry.values():
        try:
            table_names.append(clazz.__tablename__)
            classes.append(clazz)
        except:
            pass
    for table in db.metadata.tables.items():
        if table[0] in table_names:
            models.append(classes[table_names.index(table[0])])
    

    Where models is the list of models registed on your database.

    The try catch is required because a <sqlalchemy.ext.declarative.clsregistry._ModuleMarker object> will be included in the for clazz in ... loop, and it doesn't have a __tablename__ attribute.