How to print all columns in SQLAlchemy ORM

This is an old post, but I ran into a problem with the actual database column names not matching the mapped attribute names on the instance. We ended up going with this:

from sqlalchemy import inspect
inst = inspect(model)
attr_names = [c_attr.key for c_attr in inst.mapper.column_attrs]

Hope that helps somebody with the same problem!


Building on Rodney L's answer:

model = MYMODEL
columns = [m.key for m in model.__table__.columns]

Take a look at SQLAchemy's metadata reflection feature.

A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database. This process is called reflection.


Probably the shortest solution (see the recent documentation):

from sqlalchemy.inspection import inspect
columns = [column.name for column in inspect(model).c]

The last line might look more readable, if rewrite it in three lines:

table = inspect(model)
for column in table.c:
    print column.name