python - 在 sqlalchemy 中按年、月、日分组

标签 python sqlalchemy

我要

DBSession.query(Article).group_by(Article.created.month).all()

但是这个查询不能用

如何使用 SQLAlchemy 执行此操作?

最佳答案

假设你的数据库引擎实际上支持像MONTH()这样的函数,你可以试试

import sqlalchemy as sa
DBSession.query(Article).group_by( sa.func.year(Article.created), sa.func.month(Article.created)).all()

否则你可以在 python 中分组

from itertools import groupby

def grouper( item ): 
    return item.created.year, item.created.month
for ( (year, month), items ) in groupby( query_result, grouper ):
    for item in items:
        # do stuff

关于python - 在 sqlalchemy 中按年、月、日分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14955769/

相关文章:

python - clr.AddReferenceToFile() 在 IronPython 2.7 中失败

sqlalchemy - 如何将 marshmallow-sqlalchemy 与异步代码一起使用?

postgresql - PostgreSQL JSONB 中的日期时间对象

python - 为什么我会收到 SQLAlchemy 嵌套回滚错误?

python - Pandas Group By,使用行和列中的索引定义输出

python - 如何将 SciPy 稀疏矩阵转换为字典

python - 如何通过在 NumPy 中使用切片来反转二维矩阵的值?

python - SQLAlchemy 的正确模型定义是什么以避免错误消息 : AttributeError: 'InstrumentedList' object has no attribute'?

python - 在多个 uWSGI 进程中使用 Flask-SQLAlchemy

python - Django get_queryset 过滤 pk 上的对象