我可以使用SQLAlchemy使用聚合表达式吗? [英] Can I use aggregate expressions using SQLAlchemy?
本文介绍了我可以使用SQLAlchemy使用聚合表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PostgreSQL具有聚合表达式,例如 count(*)过滤器(状态为成功)
。如何使用SQLAlchemy生成此类表达式?
PostgreSQL have aggregate expressions, e.g. count(*) FILTER (WHERE state = 'success')
. How can I generate such expressions using SQLAlchemy?
推荐答案
假设我有模型 Machine
具有布尔值 active
的字段,并希望通过 active = true
Suppose I have a model Machine
with a boolean field active
, and would like to filter the count by active = true
from models import db, Machine
from sqlalchemy.sql import func
query = db.session.query(
func.count(Machine.id).filter(Machine.active == True)
.label('active_machines')
)
我们可以查看生成的SQL查询:
We can look at the generated SQL query:
>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines
FROM machine
这对于其他聚合函数(如 func.avg
, func.sum
This should work the same for the other aggregate functions like func.avg
, func.sum
, etc
func.count(Machine.id).filter(Machine.active == True)
的简称:
from sqlalchemy import funcfilter
funcfilter(func.count(Machine.id), Machine.active == True)
这篇关于我可以使用SQLAlchemy使用聚合表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文