gamp gamp -4 years ago 190
Python Question

group by year, month, day in a sqlalchemy

I want "DBSession.query(Article).group_by(Article.created.month).all()"

But this query can't using

How do I do this using SQLAlchemy?

Answer Source

assuming you db engine actually supports functions like MONTH(), you can try

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

else you can group in python like

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download