从一个由 dict 属性 FLASK 组织的 SQLAlchemy 查询返回多个列表

Returning multiple lists from one SQLAlchemy query organized by a dict attribute FLASK

我正在尝试编写一个 python 函数,它从数据库接收所有 VolunteerReports 的列表,然后根据它们的“report_category",和 returns 一个里面有很多列表的字典。

我当前的函数:

def get_volunteer_reports_for_client(volunteer_id, client_id):
    reports_obj = {}

    volunteer_reports = db_session.query(VolunteerReport).filter(
        VolunteerReport.volunteer_id == volunteer_id, \
            VolunteerReport.client_id == client_id).all()

    if not volunteer_reports:
        return []

    res = [volunteer_report_schema.dump(volunteer_report) for volunteer_report in volunteer_reports]

    for r in res:
        reports_obj[r['report_category']] = [r]

    return reports_obj

res returns 列表如下所示:

[
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.538363",
        "id": 1,
        "report": "This is the first report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:52.623236",
        "id": 2,
        "report": "This is the SECOND report",
        "report_category": "Client Assigned",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:41:59.493851",
        "id": 3,
        "report": "This is the THIRD report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    },
    {
        "client_id": 24,
        "created_at": "2022-02-10 16:43:06.364411",
        "id": 4,
        "report": "This is the FOURTH report",
        "report_category": "Fulfilled The Need",
        "volunteer_id": 23
    }
]

reports_obj 当前 returns 这个:

{
    "Client Assigned": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:41:52.623236",
            "id": 2,
            "report": "This is the SECOND report",
            "report_category": "Client Assigned",
            "volunteer_id": 23
        }
    ],
    "Fulfilled The Need": [
        {
            "client_id": 24,
            "created_at": "2022-02-10 16:43:06.364411",
            "id": 4,
            "report": "This is the FOURTH report",
            "report_category": "Fulfilled The Need",
            "volunteer_id": 23
        }
    ]
}

此时,它省略了一些条目,只返回带有“report_category”的最后一个索引条目。有什么建议吗?

在循环的每次迭代中,您都会用 [r] 的新列表覆盖该类别中的当前字典列表。如果键已经存在,则需要将当前字典附加到列表中,否则创建一个新列表。

for r in res:
    category = r['report_category']
    if category in reports_obj:
        reports_obj[category].append(r)
    else:
        reports_obj[category] = [r]