get table columns from sqlAlchemy table model

断了今生、忘了曾经 提交于 2019-11-30 01:10:47

问题


I have a table where I would like to fetch all the column names however after browsing the interwebs I could not find a way that works. This is what my table looks like:

class myTable(Base):
    __tablename__ = 'myTable'

    col1 = Column(Integer, primary_key=True)
    col2 = Column(Unicode(10))
    col3 = Column(Integer)

    col4 = Column(Numeric(10, 6))
    col5 = Column(Numeric(6,3))
    col6 = Column(Numeric(6,3))

    child = relationship('tChild',
                          backref=backref('children'))

I would like to be able to print all the column names from a for loop. ex:

"col1", "col2", "col3".... etc

This is pretty easy with regular sql but I can't seem to figure out how to do it using sqlAlchemy table models


回答1:


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]


来源:https://stackoverflow.com/questions/24959589/get-table-columns-from-sqlalchemy-table-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!