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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -