简体   繁体   中英

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.

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. You can try to remove ordering, you can read about this in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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