So, lets say I’ve got some table:
from sqlalchemy import (
Integer,
)
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy import func, select
some_table = Table(
"some_table",
Column("id", Integer, primary_key=True),
Column("first_col", Integer),
Column("second_col", ARRAY(Integer)),
)
And, I want to take both first_col
and second_col
and like aggregate them, I can show what I want in python code:
def get_some_stuff_and_aggregate():
query = (
select(
[
some_table.c.first_col,
some_table.c.second_col,
]
)
.select_from(some_table)
)
# execute query here... it's not important here
query_res = ...
res_dict = {}
for some_obj in query_res:
for some_ids in (
[some_obj.first_col],
some_obj.second_col,
):
for some_id in some_ids:
if some_id in res_dict:
res_dict[some_id] += 1
else:
res_dict[some_id] = 1
return res_dict
But, I guess I can do this at the SQL (ORM) level without this dirty and slow python aggregation, can you please help me? How to do it better, using ORM
?