You are probably doing everything right, but getting empty arrays first. In your previous query you used in-python filtering (len(x[1]) > 1
). You can print Query
expression before executing it to make sure.
You should probably add a having
clause to you base query:
from sqlalchemy import Integer
from sqlalchemy.dialects.postgresql import ARRAY
cats_agg = func.array_agg(ProductCategory.id, type_=ARRAY(Integer)).label('cats')
prods = (
session.query(
Product.id.label('id'),
cats_agg,
.outerjoin(
ProductCategory,
ProductCategory.product_id == Product.id)
.group_by(Product.id)
.having(func.array_length(cats_agg, 1) > 1)
.subquery()
)
Then you won't need in-python filtering either.