我想跟踪每年在给定年份范围内出生的动物数量。所以我也许能够确定哪一年出生的动物最多。我将这些数据用于图形报告。
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
]
它没有添加总数,也没有按年份分组。
最佳答案
可能您在动物模型的元类中有排序字段,因此将附加字段添加到分组依据并生成错误的结果。您可以尝试删除排序,您可以在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()
也不需要第二个值。
关于python - 获取给定年份范围内的年计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45342925/