简体   繁体   English

从 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'))

I would like to be able to print all the column names from a for loop.我希望能够从 for 循环中打印所有列名。 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使用常规 sql 这很容易,但我似乎无法弄清楚如何使用 sqlAlchemy 表模型来做到这一点

You get all of the columns from __table__.columns :您从__table__.columns获得所有列:

myTable.__table__.columns

or或者

myTable.__table__.c

The columns would be in format myTable.col1 (table name is included).列的格式myTable.col1 (包括表名)。 If you want just column names, get the .key for each column:如果您只需要列名,请获取每列的.key

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

Below is a general as_dict implementation for an sqlalchemy table based on @ChaimG answer.下面是基于@ChaimG 答案的 sqlalchemy 表的一般as_dict实现。 And an additional example of a __repr__ that is implemented using it.还有一个使用它实现的__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})>"

Since this question is pretty high on search engines, I want to add, that if you are using core, you can get the columns using由于这个问题在搜索引擎上相当高,我想补充一点,如果您使用的是核心,您可以使用

your_table.c

If you are using ORM like OP, the accepted answer works.如果您使用像 OP 这样的 ORM,则接受的答案有效。

Understanding that columns are class members, they are therefore stored in the __dict__ attribute of the class.了解列是类成员,因此它们存储在类的__dict__属性中。 Therefore, myTable.__dict__.keys() will give you a list of columns, in addition to other class members.因此, myTable.__dict__.keys()将为您提供除其他类成员之外的列列表。

This is helpful for desiring to know the members / methods of any class you are working with.这有助于了解您正在使用的任何类的成员/方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM