get table columns from sqlAlchemy table model get table columns from sqlAlchemy table model python python

get table columns from sqlAlchemy table model


You get all of the columns from __table__.columns:

myTable.__table__.columns

or

myTable.__table__.c

The columns would be in format myTable.col1 (table name is included). If you want just column names, get the .key for each column:

[column.key for column in myTable.__table__.columns]


Below is a general as_dict implementation for an sqlalchemy table based on @ChaimG answer. And an additional example of a __repr__ that is implemented using it.

from orm.base import Baseclass MyTable(Base):    __tablename__ = 'table_name'    # Columns go here.....    def as_dict(self):        """        Helper function that allows traversing the table's instance columns as key values        :return: (key, value) iterator        """        for key in self.__table__.columns.keys():            value = self.__getattribute__(key)            yield key, value    def __repr__(self):        """        General __repr__ implementation for an sqlalchemy table        """        values = []        for key, value in self.as_dict():            key_value_str = f"{key}={value}"            values.append(key_value_str)        values_str = ", ".join(values)        cls_name = self.__class__.__name__        return f"<{cls_name}({values_str})>"