简体   繁体   English

获取给定年份内的年度计数

[英]Get annual count within the given range of years

I want to track the number of animals born within the given range of years annually. 我想跟踪在给定年份内每年出生的动物数量。 So i may be able to determine which year has the most animals born. 因此,我也许能够确定哪一年出生的动物最多。 I am using this data for graphic reports. 我将此数据用于图形报告。

class Animal(models.Model):
    # omitted fields..
    date_of_birth = models.DateField()

Now the given years would be 2015 to 2017. I would like to get the summary of animal born within that years. 现在给定的年份是2015年到2017年。我想获得那几年内出生的动物的摘要。

Eg 例如

[ 
   {'year': 2015, total: 10},
   {'year': 2016, total: 15}
   {'year': 2017, total: 4}
]

So far here is what i did: 到目前为止,这是我所做的:

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')

But got this: 但是得到这个:

[
    {
        "total": 1,
        "year": 2015
    },
    {
        "total": 1,
        "year": 2015
    },
    {
        "total": 1,
        "year": 2015
    },
    {
        "total": 1,
        "year": 2015
    },
    ... and so on to 2017
]

It didn't add the total and it didn't grouped by year. 它没有添加总数,也没有按年份分组。

Probably you have ordering field in Meta class for Animal model, so additional field added to group by and generate wrong result. 可能您在动物模型的Meta类中具有排序字段,因此将其他字段添加到分组依据并生成错误的结果。 You can try to remove ordering, you can read about this in docs : 您可以尝试删除订单,可以在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()

Also second values not needed. 另外,不需要第二个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM