sqlalchemy - 按关系中的项目数过滤结果

标签 sqlalchemy

假设我有这两个模型:

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)

我想检索所有 Client至少有 1 Invoice并且少于 20 Invoice .
我希望它像这样工作:
Client.query.join(Invoice).filter(and_(Invoice.count() > 1, Invoice.count() <= 20))

或者甚至这会很好:
Client.query.join(Invoice).filter(and_(count_(Invoice) > 1, count_(Invoice) <= 20))

但当然,事情不可能这么简单。 .count()显然不能从那里工作,我找不到 count_()sqlalchemy.func .

最佳答案

感谢周围的同事和代码,我们让它工作了:

    client = Client.query\
        .outerjoin(Client.invoices)\
        .group_by(Client)\
        .having(\
             func.and_(\
                 func.count_(Client.invoices) >= 1)\
                 func.count_(Client.invoices) <= 20)\
             )
        ).all()

我希望它可以帮助某人!

关于sqlalchemy - 按关系中的项目数过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38637886/

相关文章:

python - 在 SQLAlchemy 中执行连接时出错 'Please specify the ' onclause' of this join explicitly'。

python - Tornado 的 ORM

python - 将 Pandas DataFrame 转换为 VALUES sql 语句

python - 设置数据库的添加、删除和更改日志

postgresql - Python SqlAlchemy : Data are inserted with NULL values instead of specified values

python - SQLAlchemy:使用 `and` 和 `or` 时出现意外结果

python - SQLAlchemy 自省(introspection)

python - 是否可以在 python 中重置 sqlalchemy 查询对象的 group_by 项?

python - 将 MySQL 多边形上传并获取到 Python

python - 单个 python 脚本文件中的 sqlalchemy