Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return SQLAlchemy results as dicts instead of lists

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)]
like image 866
Arti Avatar asked Jul 25 '15 08:07

Arti


People also ask

What SQLAlchemy execute return?

SQLAlchemy execute() return ResultProxy as Tuple, not dict.

What does all () do in SQLAlchemy?

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.

What is lazy SQLAlchemy?

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.

What is _sa_instance_state?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.


2 Answers

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}]
like image 169
davidism Avatar answered Sep 20 '22 08:09

davidism


in Python 3.7 / SQLAlchemy 1.3.18 this works for me:

return [dict(r) for r in results]
like image 34
Leon Starr Avatar answered Sep 22 '22 08:09

Leon Starr