Shift N' Tab Shift N' Tab - 1 year ago 47
Python Question

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.

E.g.

[
{'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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download