getting columns attributes in declarative style with sqlalchemy

tres.bailey at gmail.com tres.bailey at gmail.com
Tue Nov 1 15:26:19 EDT 2011


Hi Gabriele,

I'm not an Alchemy expert, but I have used the ColumnProperty of the model/column objects to solve this problem in the past.  So to get the column name for the description column in your example above, you would use the following syntax:

Country.description.property.columns[0].name

And this would avoid having to use additional objects than the one you're working on.  The ColumnProperty object (and the Column object attribute it contains) will provide you with information such as column name, type, default vals, primary_key, and nullable.  You could also get more generic by iterating through your model object's __table__ attribute and grab each column:

[col.name for col in Country.__table__.columns._all_cols]


More information can be found here:
http://www.sqlalchemy.org/docs/core/schema.html?highlight=schema.column#sqlalchemy.schema.Column
and
http://www.sqlalchemy.org/docs/orm/internals.html?highlight=columnproperty#sqlalchemy.orm.properties.ColumnProperty




More information about the Python-list mailing list