从 sqlAlchemy 表模型中获取表列 [英] get table columns from sqlAlchemy table model
问题描述
我有一个表,我想在其中获取所有列名,但是在浏览互联网后我找不到有效的方法.这是我的表的样子:
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'))
我希望能够打印 for 循环中的所有列名.例如:
I would like to be able to print all the column names from a for loop. ex:
"col1", "col2", "col3".... etc
使用常规 sql 这很容易,但我似乎无法弄清楚如何使用 sqlAlchemy 表模型来做到这一点
This is pretty easy with regular sql but I can't seem to figure out how to do it using sqlAlchemy table models
推荐答案
您从 __table__.columns
中获取所有列:
You get all of the columns from __table__.columns
:
myTable.__table__.columns
或
myTable.__table__.c
列的格式为 myTable.col1
(包括表名).如果您只需要列名,请获取每列的 .key
:
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]
这篇关于从 sqlAlchemy 表模型中获取表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!