sqlalchemy - Filter results by count of items in relationship -
let's have these 2 models :
def client(db.model): id = db.column(db.integer, primary_key=true) invoices = db.relationship('invoice', backref='client') def invoice(db.model): id = db.column(db.integer, primary_key=true) i'd retrieve client @ least 1 invoice , less 20 invoice. expecting work :
client.query.join(invoice).filter(and_(invoice.count() > 1, invoice.count() <= 20)) or nice :
client.query.join(invoice).filter(and_(count_(invoice) > 1, count_(invoice) <= 20)) but of course, can't simple. .count() can't work there , can't find count_() in sqlalchemy.func.
thanks coworkers , code lying around, got working:
client = client.query\ .outerjoin(client.invoices)\ .group_by(client)\ .having(\ func.and_(\ func.count_(client.invoices) >= 1)\ func.count_(client.invoices) <= 20)\ ) ).all() i hope helps someone!
Comments
Post a Comment