The FinancialContent Network     SocialPicks Community   |   MarketMinute Monitor   |   MarketMinute Market Updates   |   MarketMinute Stock News
SocialPicks
   Sign Up   |   Log In   |   What is SocialPicks?     

howto: group by in django

 Jan 05, 2009 05:23 AM UTC
X1piuxx1vymtqtyfiu50x-rtkknjre2iobelalogd0k0s5ddytbdwcrzieb3h9c8dukcv8smcahnulc7mrpgcloig95xozfgpj0kbdxryqzr0a
Return Risk
-11.40% HIGH
Sr. Analyst

Graphic_arrow1 Via Evan Reiser's Blog:  

Django doesnt officially yet support group by, however the code to acomplish this is actually hidden inside.  If you had a model that tracked registrations, which contained a FK to the user that refered the new user such as:

class Registration(models.Model):
        ...
        referer = models.ForeignKey(User,null=True,blank=True)


>>> from registration.models import Registration

>>> query_set = Registration.objects.extra(select={'count': 'count(1)'}, order_by=['-count'],where=['referer_id is not null']).values('count', 'referer')  
>>> query_set.query.group_by = ['referer_id']

>>> for row in query_set:
...  print row                                                                                                                                  
... 
{'count': 26L, 'referer': 6384}
{'count': 4L, 'referer': 6871}
{'count': 3L, 'referer': 9993}
{'count': 2L, 'referer': 7804}
{'count': 2L, 'referer': 7892}
{'count': 2L, 'referer': 9699}
{'count': 1L, 'referer': 6111}
{'count': 1L, 'referer': 7821}
{'count': 1L, 'referer': 5025}


this is as of 
Last Changed Rev: 9037
Last Changed Date: 2008-09-15 14:06:02 -0400 (Mon, 15 Sep 2008)



 Graphic_website1 Read the rest of original post »



Add Comment

Be the first to comment on this story and earn 2 points.

Your Comment



IN THE PRESS
Press_forbes Press_washingtonpost Press_wsj Press_npr Press_techcrunch