'Returning multiple lists from one SQLAlchemy query organized by a dict attribute FLASK
I am trying to write a python function that receives a list of all VolunteerReports from a DB and then organizes them into separate lists based on their "report_category", and returns one dict with many lists inside.
my current function:
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 a list that looks like so:
[
{
"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 currents returns this:
{
"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
}
]
}
At this point, it is omitting some of the entries and only returning the last indexed entry with that "report_category". Any advice?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
