Josh Parinussa
Josh Parinussa

Reputation: 643

How to get average from each hour in one week in django?

I have a task to get the average some data in each hour inside a week.

{'hour': 0, 'count': 70}
{'hour': 1, 'count': 92}
{'hour': 2, 'count': 94}
{'hour': 3, 'count': 88}
{'hour': 4, 'count': 68}
{'hour': 5, 'count': 69}
{'hour': 6, 'count': 70}
{'hour': 7, 'count': 82}
{'hour': 8, 'count': 91}
{'hour': 9, 'count': 67}
{'hour': 10, 'count': 92}
{'hour': 11, 'count': 100}
{'hour': 12, 'count': 92}
{'hour': 13, 'count': 55}
{'hour': 14, 'count': 61}
{'hour': 15, 'count': 47}
{'hour': 16, 'count': 36}
{'hour': 17, 'count': 19}
{'hour': 18, 'count': 11}
{'hour': 19, 'count': 6}
{'hour': 20, 'count': 3}
{'hour': 21, 'count': 9}
{'hour': 22, 'count': 27}
{'hour': 23, 'count': 47}

The data above is the result of this query

result = Device.objects.filter(station__in=stations, created_at__range=(start_date, end_date)) \
            .extra({'hour': 'hour(created_at)'}) \
            .values('hour').annotate(count=Count('id')).order_by('hour')

the result is queryed by 7 days range, what I want to do is get the average for each hour in 7 days, exampe the total of count in hour 0 is 70 then i need to average it from 7 days.

Any suggestion?

Upvotes: 2

Views: 713

Answers (1)

ruddra
ruddra

Reputation: 51978

Probably you can try like this with F() expression:

from django.db.models import F, ExpressionWrapper, DecimalField    

result = result.annotate(average=ExpressionWrapper(F('count')/7, output_field=DecimalField()))

Upvotes: 1

Related Questions