4
我需要創建一個報表,我可以獲取一年中每個月的值。Django按組計算
models.py
class Ask(models.Model):
team = models.CharField(max_length=255)
date = models.DateField()
在球隊只有三個可能的值:A,B,C
如何計算每個月多少次加個人的團隊?
我想爲每年生成一份報告。
我需要創建一個報表,我可以獲取一年中每個月的值。Django按組計算
models.py
class Ask(models.Model):
team = models.CharField(max_length=255)
date = models.DateField()
在球隊只有三個可能的值:A,B,C
如何計算每個月多少次加個人的團隊?
我想爲每年生成一份報告。
我建議您將month
字段添加到您的模型並在save
月通過那裏。這是幫助你運行這個命令:
from django.db.models import Count
Ask.objects.filter(date__year='2013').values('month', 'team').annotate(total=Count('team'))
另一種方法是使用從日期字段extra參數和提取一個月:
from django.db.models import Count
Ask.objects.filter(date__year='2013').extra(select={'month': "EXTRACT(month FROM date)"}).values('month', 'team').annotate(Count('team'))
但EXTRACT方法取決於數據庫和例如dont`t工作對於EXTRACT,SQLite
+1。 [在SQLite中你必須使用](http://www.sqlite.org/lang_datefunc.html)'STRFTIME(date,「%m」)' – 2013-04-05 08:42:05
工作正常,但只有如何添加到模板才能使它看起來像這樣:2013-01球隊A = 2,2013-02球隊A = 1,2013-03球隊A = 7 ...現在我有{'team__count':5,'team':u'A', 'month':3.0} – MalT 2013-04-05 09:11:30
訪問模板中的dict值閱讀此:http://stackoverflow.com/questions/8000022/django-template-how-to-lookup-a-dictionary-value-with-a-variable – 2013-04-05 09:23:56