Dr. John A Zoidberg
Dr. John A Zoidberg

Reputation: 1248

How to get column types of an existing, named table from SQLAlchemy

How can I represent this query in SQLAlchemy?

SELECT COLUMN_NAME, DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'foo'

Upvotes: 1

Views: 4634

Answers (2)

Blue Moon
Blue Moon

Reputation: 4651

def get_data_types(model):
'''return dictionary with column name as key and data type as value'''
    d = {}
    for c in model.__table__.columns:
        d[str(c.name)] = str(c.type)

    return d

where model is the sqlalchemy orm table.

Upvotes: 0

polku
polku

Reputation: 1590

Mb, I didn't understood you meant the database types. If it's a mapped table you can iterate columns like this:

for c in foo.__table__.columns:
    print(c.type)

Upvotes: 4

Related Questions