将 SQLAlchemy 结果作为字典而不是列表返回 [英] Return SQLAlchemy results as dicts instead of lists

查看:98
本文介绍了将 SQLAlchemy 结果作为字典而不是列表返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我检查查询结果时,它看起来像一个列表列表.我想返回一个将列名映射到结果值的字典列表.如何将结果行转换为字典?

When I examine the results of a query, it looks like a list of lists. I want to return a list of dicts mapping column names to result values. How can I convert the result rows to dicts?

results = db.session.query(
    PendingPost.campaign_id.label('campaign_id'),
    Campaign.title.label('title'),
    sqlalchemy.func.count(PendingPost.status).label('status_count'),
).join(
    Campaign, Campaign.id == PendingPost.campaign_id,
).join(
    Areas, Areas.id == PendingPost.area_id
).filter(
    sqlalchemy.func.month(PendingPost.creation_date) == datetime.datetime.utcnow().month
).group_by(
    PendingPost.status,
    PendingPost.campaign_id,
).all()

print(results)
[(3, 'campaign title', 1),
 (4, 'campaign title', 1)]

推荐答案

结果看起来像元组/列表,但它们实际上是一个特殊的KeyedTuple 对象.使用 _asdict() 方法将每一行转换为字典.

The results look like tuples/lists, but they are actually a special KeyedTuple object. Use the _asdict() method to convert each row to a dict.

return [r._asdict() for r in results]
[{'campaign_id': 3, 'title': 'campaign title', 'status_count': 1},
 {'campaign_id': 4, 'title': 'campaign title', 'status_count': 1}]

这篇关于将 SQLAlchemy 结果作为字典而不是列表返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆