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?


Solution 1:

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

Solution 2:

I know this question is ancient, but for the benefit of anyone searching for solutions, here's another strategy for databases that don't support functions like MONTH():

db.session.query(sa.func.count(Article.id)).\
    group_by(sa.func.strftime("%Y-%m-%d", Article.created)).all()

Essentially this is turning the timestamps into truncated strings that can then be grouped.

If you just want the most recent entries, you can add, for example:

    order_by(Article.created.desc()).limit(7)

Following this strategy, you can easily create groupings such as day-of-week simply by omitting the year and month.

Solution 3:

THC4k answer works but I just want to add that query_result need to be already sorted to get itertools.groupby working the way you want.

query_result = DBSession.query(Article).order_by(Article.created).all()

Here is the explanation in the itertools.groupby docs:

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.