从 sqlAlchemy 表模型中获取表列 [英] get table columns from sqlAlchemy table model

查看:32
本文介绍了从 sqlAlchemy 表模型中获取表列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,我想在其中获取所有列名,但是在浏览互联网后我找不到有效的方法.这是我的表的样子:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆