Don Smythe
Don Smythe

Reputation: 9804

SqlAlchemy table name reflection using an efficient method

I am using the code below to extract table names on a database at a GET call in a Flask app.:

session = db.session()
qry = session.query(models.BaseTableModel) 
results = session.execute(qry)
table_names = []
for row in results:
    for column, value in row.items():
        #this seems like a bit of a hack
        if column == "tables_table_name":
            table_names.append(value)
print('{0}: '.format(table_names))

Given that tables in the database may added/deleted regularly, is the code above an efficient and reliable way to get the names of tables in a database?

Upvotes: 0

Views: 122

Answers (1)

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

One obvious optimization is to use row["tables_table_name"] instead of second loop.

Assuming that BaseTableModel is a table, which contains names of all other tables, than you're using the fastest approach to get this data.

Upvotes: 1

Related Questions