从 sqlAlchemy 表模型中获取表列

问题描述 投票:0回答:5

我有一张表,我想在其中获取所有列名,但是在浏览了互联网之后,我找不到可行的方法。这是我的桌子的样子:

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 循环中打印所有列名。例如:

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

这对于常规 sql 来说非常简单,但我似乎无法弄清楚如何使用 sqlAlchemy 表模型来做到这一点

python sqlalchemy pyramid
5个回答
50
投票

您从

__table__.columns
获得所有列:

myTable.__table__.columns

myTable.__table__.c

列的格式为

myTable.col1
(包括表名)。如果您只想要列名,请为每列获取
.key

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

4
投票

下面是基于@ChaimG 答案的 sqlalchemy 表的一般

as_dict
实现。以及使用它实现的
__repr__
的附加示例。

from orm.base import Base


class 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})>"

1
投票

由于这个问题在搜索引擎上的排名很高,我想补充一点,如果您使用的是核心,则可以使用以下方法获取列

your_table.c

如果您正在使用像 OP 这样的 ORM,则接受的答案有效。


0
投票

您从

__table__.columns
获得所有列:

确实如此,但您应该避免访问对象的“受保护”和“私有”成员。如果您尝试这样做,您的 linter 应该会抱怨。

访问表列的正确方法是通过 SQLAlchemy 的Runtime Inspection API。来自文档:

inspect() 的返回值保证遵守文档化的 API,从而允许构建在 SQLAlchemy 配置之上的第三方工具以向前兼容的方式构建。

你可以这样使用它:

from sqlalchemy import inspect

# ###########################################
# Inspect a Mapped Ojbect
#  https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapper-inspection-mapper
# ###########################################
mapped_object = inspect(myTable)
mapped_object.columns.items()
[('col1',
  Column('col1', Integer(), table=<myTable>, primary_key=True, nullable=False)),
 ('col2', Column('col2', Unicode(length=10), table=<myTable>)),
 ('col3', Column('col3', Integer(), table=<myTable>)),
 ('col4', Column('col4', Numeric(precision=10, scale=6), table=<myTable>)),
 ('col5', Column('col5', Numeric(precision=6, scale=3), table=<myTable>)),
 ('col6', Column('col6', Numeric(precision=6, scale=3), table=<myTable>))]

[column.key for column in mapped_object.columns]
['col1', 'col2', 'col3', 'col4', 'col5', 'col6']

# ###########################################
# Inspect a Mapped Instance
#  https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapper-inspection-instancestate
# ###########################################
my_table = myTable(...)
mapped_instance = inspect(my_table)

# Notice: This collection include 'child'.  The columns from the mapped object did not.
mapped_instance.attrs.items()
[('child', <sqlalchemy.orm.state.AttributeState at 0xffff9c748130>),
 ('col1', <sqlalchemy.orm.state.AttributeState at 0xffff9c7481f0>),
 ('col2', <sqlalchemy.orm.state.AttributeState at 0xffff9c748190>),
 ('col3', <sqlalchemy.orm.state.AttributeState at 0xffff9c7482b0>),
 ('col4', <sqlalchemy.orm.state.AttributeState at 0xffff9c748100>),
 ('col5', <sqlalchemy.orm.state.AttributeState at 0xffff9c748160>),
 ('col6', <sqlalchemy.orm.state.AttributeState at 0xffff9c748370>)]

# Notice: You can get the same collection as the mapped object returned by going through the mapper.
mapped_instance.mapper.columns.items()
[('col1',
  Column('col1', Integer(), table=<myTable>, primary_key=True, nullable=False)),
 ('col2', Column('col2', Unicode(length=10), table=<myTable>)),
 ('col3', Column('col3', Integer(), table=<myTable>)),
 ('col4', Column('col4', Numeric(precision=10, scale=6), table=<myTable>)),
 ('col5', Column('col5', Numeric(precision=6, scale=3), table=<myTable>)),
 ('col6', Column('col6', Numeric(precision=6, scale=3), table=<myTable>))]



-1
投票

了解列是类成员,因此它们存储在类的

__dict__
属性中。 因此,
myTable.__dict__.keys()
会给你一个列的列表,除了其他班级成员。

这有助于了解您正在使用的任何类的成员/方法。

© www.soinside.com 2019 - 2024. All rights reserved.