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)]
SQLAlchemy execute() return ResultProxy as Tuple, not dict.
all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.
Lazy loading refers to objects are returned from a query without the related objects loaded at first. When the given collection or reference is first accessed on a particular object, an additional SELECT statement is emitted such that the requested collection is loaded.
_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.
The results look like tuples/lists, but they are actually a special Row
object (KeyedTuple
for SQLAlchemy < 1.4). 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}]
in Python 3.7 / SQLAlchemy 1.3.18 this works for me:
return [dict(r) for r in results]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With