我想跟蹤每年在給定範圍內出生的動物數量。所以我可以確定哪一年出生的動物最多。我正在將這些數據用於圖形報告。在給定的年份範圍內獲得年度計數
class Animal(models.Model):
# omitted fields..
date_of_birth = models.DateField()
現在給定的年份將是2015年到2017年。我想了解那些年內出生的動物概要。
E.g.
[
{'year': 2015, total: 10},
{'year': 2016, total: 15}
{'year': 2017, total: 4}
]
到目前爲止,這裏是我做過什麼:
Animal.objects.filter(
date_of_birth__year__range = (
'2017', '2018'
)
).extra(
select={'year': 'YEAR(date_of_birth)'}
).values('year').annotate(total=Count('id')).values('year', 'total')
但得到這個:
[
{
"total": 1,
"year": 2015
},
{
"total": 1,
"year": 2015
},
{
"total": 1,
"year": 2015
},
{
"total": 1,
"year": 2015
},
... and so on to 2017
]
它沒有加總並沒有按年份進行分組。
哇,我很驚訝男人感謝您的回答它提供了正確的解決方案 –