Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group by year, month, day in a sqlalchemy

Tags:

I want

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

But this query can't using

How do I do this using SQLAlchemy?

like image 990
gamp Avatar asked Sep 03 '09 01:09

gamp


1 Answers

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 
like image 100
Jochen Ritzel Avatar answered Sep 22 '22 17:09

Jochen Ritzel