SQLAlchemy array aggregate of objects

31 views
Skip to first unread message

Wojtek K

unread,
Nov 5, 2020, 7:42:59 AM11/5/20
to sqlalchemy
Hi All, I'm trying to find the solution but with no success

I have 2 tables related through assoc table

table a
id   |name    |
-----|--------|
1    |example |

assoc
id   |a_id | b_id |
-----|-----|------|
1    |1    |1     |
2    |1    |2     |

table b  
id   |name     |
-----|---------|
1    |example1 |
2    |example2 |  


Of course I've mapped classes through orm.
I want to select all records from a join b and then group by a object and aggregate all related records from b to an array of b objects:

( <model.TableA>, [<model.TableB>, <model.TableB>] )

So far I only found a solution of using some mix of postgresql dialect and sa 
like:
postgresql.array_agg(func.json_build_object("id", TableB.id, "name", TableB.name))
and I can produce

( <model.TableA>, [{"id":1, "name": "example1"}, {"id":2, "name": "example2"}] )  

but ideally would by the array of objects

Mike Bayer

unread,
Nov 5, 2020, 1:45:52 PM11/5/20
to noreply-spamdigest via sqlalchemy
I think what's important here is to come up with the exact SQL string you'd like to create first, then if you can share that here we can show you how SQLAlchemy can render it from the expression language.    As far as working with the PG functions someone else here might know or you can try stackoverflow.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages