Can I use aggregate expressions using SQLAlchemy?

本小妞迷上赌 提交于 2020-03-16 06:16:08

问题


PostgreSQL have aggregate expressions, e.g. count(*) FILTER (WHERE state = 'success'). How can I generate such expressions using SQLAlchemy?


回答1:


Suppose I have a model Machine with a boolean field active, and would like to filter the count by active = true

Using func.count(...).filter(...)

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')
)

We can look at the generated SQL query:

>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines 
FROM machine

This should work the same for the other aggregate functions like func.avg, func.sum, etc

Longer syntax using funcfilter(count(...), filter)

func.count(Machine.id).filter(Machine.active == True) is short hand for:

from sqlalchemy import funcfilter

funcfilter(func.count(Machine.id), Machine.active == True)


来源:https://stackoverflow.com/questions/47324538/can-i-use-aggregate-expressions-using-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!