[英]Get annual count within the given range of years
我想跟蹤在給定年份內每年出生的動物數量。 因此,我也許能夠確定哪一年出生的動物最多。 我將此數據用於圖形報告。
class Animal(models.Model):
# omitted fields..
date_of_birth = models.DateField()
現在給定的年份是2015年到2017年。我想獲得那幾年內出生的動物的摘要。
例如
[
{'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
]
它沒有添加總數,也沒有按年份分組。
可能您在動物模型的Meta類中具有排序字段,因此將其他字段添加到分組依據並生成錯誤的結果。 您可以嘗試刪除訂單,可以在docs中閱讀有關此內容的信息:
Animal.objects.filter(
date_of_birth__year__range = (
'2017', '2018'
)
).extra(
select={'year': 'YEAR(date_of_birth)'}
).values('year').annotate(total=Count('id')).order_by()
另外,不需要第二個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.