简体   繁体   English

无法将SQLAlchemy对象中的所有项目转换为字典中的键值

[英]Unable to Convert All Items in SQLAlchemy Object to Key-Value in Dictionary

I am trying to convert each row in a SQLAlchemy results object into a dictionary where each column header is a key. 我正在尝试将SQLAlchemy结果对象中的每一行转换成字典,其中每个列标题都是键。 Not all of the columns in my query are returned in the dictionary, though. 但是,并不是查询中的所有列都在字典中返回。 None of the columns from the "Project" table are visible. “项目”表中的所有列均不可见。

Is there an additional step needed in my for loop to unpack these columns and their values? 我的for循环中是否需要采取其他步骤来解压缩这些列及其值?

projects_for_template = (
      db.session.query(Project, func.count(Entry.id).label('entry_count'))
      .join(Entry, Project.name == Entry.project)
      .group_by(Project)
)

projects_for_template_list = []

for row in projects_for_template.all():
        row_dict = row._asdict()
        projects_for_template_list.append(row_dict)

print (projects_for_template_list)

[{'entry_count': 45L, 'Project': <Project 1>}, {'entry_count': 3L, 'Project': <Project 2>}, {'entry_count': 62L, 'Project': <Project 3>}]

I would have expected to see something like this... 我本来希望看到这样的事情...

[{'entry_count': 45L, 'project_id': 123, 'client_name': XYZcorp, 'analyst_name': Bob}, {'entry_count': 3L, 'project_id': 456, 'client_name': Acme_Inc, 'analyst_name': Jane}, {'entry_count': 62L, 'project_id': 789, 'client_name': Innotek, 'analyst_name': Michael}]

Because you are requesting for entire Project object rather than the individual fields of Project 因为你所要求的,整个Project的对象,而不是个别领域Project

projects_for_template = (
      db.session.query(Project.id,Project.client_name,func.count(Entry.id).label('entry_count'))
      .join(Entry, Project.name == Entry.project)
      .group_by(Project.id,Project.client_name) # add all the fields here
)

OR 要么

You can also iterate over the result set and convert the Project object to fetch the key values with making changes to the sql 您还可以遍历结果集并转换Project对象以对sql进行更改以获取键值

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

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