【问题标题】:Get column names Dynamically with SQLAlchemy使用 SQLAlchemy 动态获取列名
【发布时间】:2015-12-31 20:07:50
【问题描述】:

我正在使用 SQLAlchemy 查询 sqlite db,如下所示:

import db

...

results = session.query(table).all()
        for result in results:
            print result
            print "how to print column name?"

这是一个来自 db 类的 sn-p:

class Device(Base):
    __tablename__ = "devices"
    name = Column(String(250), primary_key=True)
    location = Column(String(250), nullable=False)

    def __init__(self, name, location):
        self.name = name
        self.location = location

尝试根据文档在结果上使用“.column_descriptions”会引发“'list' object has no attribute 'column_descriptions'”错误。

动态获取列名和值的正确方法是什么?我想要这个,所以我可以构建一个函数来处理所有查询的 json 转换,而不是到处重复代码。

【问题讨论】:

标签: python sql sqlite python-2.7 sqlalchemy


【解决方案1】:

您可以在代码中使用Device.__table__.columns 获取Device 模型中的列列表。这些是Column 对象,您可以在迭代时在它们上使用.name 来获取名称。然后在查询的时候,就可以使用getattr或者其他的东西来获取你需要的值。

编辑:

例子:

col_names = Device.__table__.columns.keys()  # This gets the column names
sample_row = Device.query.first()  # I just query for a random row
required_values = {name: getattr(sample_row, name) for name in col_names}
# This is a dictionary comprehension

也许您也可以使用select 语法。

EDIT2:

这是dictionary comprehension上的一篇文章

好的,所以这个字典理解的作用是它获取键作为列的名称,并将值作为我查询的示例行中相应列的值。

您想打印list,所以我们可以这样做:

用这个替换字典理解行。

print([getattr(sample_row, name) for name in col_names])

这将在列表中打印该行的值,但您不会获得列名。

但为此,您可以创建一个元组列表。

print([(name, getattr(sample_row, name)) for name in col_names])

但您更简单的方法可能是使用 SQLAlchemy 提供的 select 语法。

这里的文档:http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html#selecting

【讨论】:

  • 我能够在 for 循环中获取列名,但现在无法获取值。我在 getattr 上找不到明确的文档。我尝试了 getattr(Device, column.name) 但它没有输出值。你能举个例子吗?
  • 我用一个例子编辑了我的答案。看看这是否适合你。
  • 这个例子我有点不清楚(我是 python 新手)。您能否提供一个示例,展示如何在简单的 for in 循环中打印列名和列值?
  • 我编辑了我的答案。如果您需要更多解释,请告诉我。
  • 我收到“出现 selectQuery 错误:getattr():属性名称必须是字符串”错误。 “print sample_row”输出“”大概是因为它没有被循环,所以不是字符串值。我也不明白您使用 for in 循环的方式。能否以问题中的第一个代码 sn-p 作为起点,使其更具可读性?
猜你喜欢
  • 2012-02-15
  • 2016-05-24
  • 2019-02-14
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多