python - SQLAlchemy: filter on operator in a many-to-many relationship -
i have 2 classes many-to-many relationship, items , categories.
categories have associated value.
i query items highest categorie.value (if there any) less given value.
so far have tried queries this:
from sqlalchemy.sql import functions session.query(items).join(categories,items.categories).filter(functions.max(categories.value)<3.14).all() but in case (operationalerror) misuse of aggregate function max() error.
is there way make query?
you need group by , having instead of where filtering on aggregate.
session.query(items).join(items.categories).group_by(items.id).having(functions.max(categories.value)<3.14).all() edit: include items without category, believe can outer join , put or in having clause:
session.query(items).outerjoin(items.categories).group_by(items.id)\ .having( (functions.max(categories.value)<3.14) | (functions.count(categories.id)==0) )\ .all()
Comments
Post a Comment