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:
JavaScript
x
14
14
1
class myTable(Base):
2
__tablename__ = 'myTable'
3
4
col1 = Column(Integer, primary_key=True)
5
col2 = Column(Unicode(10))
6
col3 = Column(Integer)
7
8
col4 = Column(Numeric(10, 6))
9
col5 = Column(Numeric(6,3))
10
col6 = Column(Numeric(6,3))
11
12
child = relationship('tChild',
13
backref=backref('children'))
14
I would like to be able to print all the column names from a for loop. ex:
JavaScript
1
2
1
"col1", "col2", "col3" . etc
2
This is pretty easy with regular sql but I can’t seem to figure out how to do it using sqlAlchemy table models
Advertisement
Answer
You get all of the columns from __table__.columns
:
JavaScript
1
2
1
myTable.__table__.columns
2
or
JavaScript
1
2
1
myTable.__table__.c
2
The columns would be in format myTable.col1
(table name is included). If you want just column names, get the .key
for each column:
JavaScript
1
2
1
[column.key for column in myTable.__table__.columns]
2