简体   繁体   中英

SQLalchemy query get aggregate array of dicts

Is it possible to get an aggregate array containing dictionaries from an SQLAlchemy query? eg

session.query(
    Object.name,
    func.array_agg({Location.id: Location.name}).label('locations')
)\
    .join(Location)\
    .all()

So the expected result will be:

[
 ('Horizontal neutral circuit',
  [{143:'A5'},{145:'A8'},{765:'B12'}]),
 ('Fletcher, Lopez and Edwards',
  [{41:'A1'},{76:'B8'},{765:'B12'}]),
]

I guess you could use json_build_object() to build your dictionaries:

from sqlalchemy.dialects import postgresql

session.query(
        Object.name,
        postgresql.array_agg(
            func.json_build_object(Location.id,
                                   Location.name)).label('locations'))\
    .join(Location)\
    .group_by(Object.name)\
    .all()

with the caveat that the keys will be strings, compared to your example's integer keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM