group by year, month, day in a sqlalchemy

前端 未结 3 736
孤独总比滥情好
孤独总比滥情好 2020-11-30 05:22

I want

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

But this query can\'t using

How do I do this using SQLAlchemy

相关标签:
3条回答
  • 2020-11-30 05:22

    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
    
    0 讨论(0)
  • 2020-11-30 05:38

    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.

    0 讨论(0)
  • 2020-11-30 05:43

    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.

    0 讨论(0)
提交回复
热议问题