SQLAlchemy:自动将列名称映射到值

时间:2017-08-15 18:39:54

标签: python orm sqlalchemy flask-sqlalchemy

背景

当我想创建一个字典以将列名映射到结果中的值时,我需要单独列出每一列

,

模型是ORM映射的,不是 SQLAlchemy核心。

txt = open('b.txt').read().split('END')[0]
_, h, txt = txt.split('\n', 2)
pat = r'[\|, ,#,\,]+'
names = re.split(pat, h.strip())

pd.read_csv(
    pd.io.common.StringIO(txt),
    names=names, header=None,
    engine='python')

   A1  A2  A3  A4    A5  A6  A7     A8  A9
0   1   2   3   4  5.cd   6   7  8.dvd   9
1   1   2   3   4  5.cd   6   7  8.dvd   9
2   1   2   3   4  5.cd   6   7  8.dvd   9

问题

这对于包含许多列的表来说效率不高,也不能为其他表重用相同的代码。

我尝试了以下但无法获取列名

    result = self.session.query(Project)\
                .join(Deadline)\
                .values(Project.project_id, Project.project_name,
                    Project.project_root, Deadline.deadline_time)

    output = []
    for row in result:
        r = {}
        r['project_id'] = row.project_id
        r['project_name'] = row.project_name
        r['project_root'] = row.project_root
        r['deadline_time'] = row.deadline_time
        output.append(r)

    return output

编辑1

关于converting SQLAlchemy result into dict,有一些类似的问题。根据上面的代码,class Deadline(Base): __tablename__ = 'deadline' deadline_id = Column(Integer, primary_key = True) deadline_time = Column(String, nullable = False) class Project(Base): __tablename__ = 'project' project_id = Column(Integer, primary_key = True) project_name = Column(String, nullable = False) project_root = Column(String, nullable = False) deadline_id = Column(Integer, ForeignKey("deadline.deadline_id"), nullable=False) deadline = relationship("Deadline", primaryjoin = "Project.deadline_id == Deadline.deadline_id", backref=backref("project", uselist=False)) 不适用于ORM映射模型。

3 个答案:

答案 0 :(得分:1)

您的行是SQLAlchemy KeyedTuple。由于0.8 KeyedTuples有_asdict()方法 - 您只需使用:

output = []

for row in result:
    output.append(row._asdict())

PS。您不必在截止日期关系中指定这样一个简单的primaryjoin。 SQLAlchemy将自己确定外键。

答案 1 :(得分:0)

我相信你可以使用词典理解:

r = {k: row[k] for k in row}

将其与输出一起包含在列表解析中:

output = [{k: row[k] for k in row} for row in result]

您可能只想将值附加到列表中,而不是在每行JSON样式中重复列名。

答案 2 :(得分:0)

krassowskianswer is exactly what I need。为简洁起见,我将_asdict()应用为lambda函数。

result = self.session.query(Project)\
                .join(Deadline)\
                .values(Project.project_id, Project.project_name,
                    Project.project_root, Deadline.deadline_time)
map(lambda x: x._asdict(), result)