【问题标题】:Return field name and value from SQLAlchemy result从 SQLAlchemy 结果返回字段名称和值
【发布时间】:2018-04-08 08:31:28
【问题描述】:

如何使用 sqlalchemy 获取表列名称和值?

使用我所拥有的,我能够检索:

(2, 'blue', 'square')

但我想得到的是:

{'id': 2, 'color': 'blue', 'type': 'square'}

拜托,我看完this documentation for version 0.9后写的:

ConnectionManager.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Table, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


location = 'localhost'
engine_str = 'mysql+mysqlconnector://xx:xx@{}/xx'.format(location)
engine = sqlalchemy.create_engine(engine_str, echo=False)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()

class SelectType(object):
    """
    Server's details on database
    """
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=cc).filter_by(type=pp).all()
        return result

def select_type(e, p):
    """
    return SelectType result
    """
    try:
        return SelectType().go(session, e, p)
    except:
        raise
    finally:
        session.close()

ma​​infile.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from resources import connection_manager

if __name__ == "__main__":
    try:
for i in connection_manager.select_type('blue', 'square'):
    print(i)

重要的是要注意我正在使用 autoload

【问题讨论】:

    标签: python-3.x sqlalchemy


    【解决方案1】:

    在这里使用Query.column_descriptions

    class SelectType(object):
        def go(self, s, cc, pp):
            __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
            result = s.query(__table__).filter_by(color=environment).filter_by(type=pp)
            column_names = [c["name"] for c in result.column_descriptions]
            return [dict(zip(column_names, row)) for row in result.all()]
    

    【讨论】:

    • 完美。非常感谢
    【解决方案2】:

    我对此很陌生,所以我可能会误解您的问题。但看起来您想要 JSON 格式的数据。

    我不知道您是否可以使用 connection_manager.select_type 访问密钥,但值得尝试的一件事是:

    for k,v in connection_manager.select_type('blue', 'square'): print(k) print(v)

    其中 k 是键,v 是值。这可能是迭代它的一种可能方式。

    此问题与此处的另一篇帖子半相关:SQLAlchemy: Knowing the field names and values of a model object? 这也可能对您有所帮助。祝你好运!

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多