add enhanced feedings statistics

This commit is contained in:
Benjamin Häublein 2020-03-15 17:18:21 +01:00
parent 3316ce3c2d
commit 853ab54b8c
1 changed files with 34 additions and 13 deletions

View File

@ -5,6 +5,8 @@ from django.db.models.functions import TruncDate
from django.utils import timezone
from django.utils.translation import gettext as _
from datetime import date, datetime, time
from core import models
@ -170,10 +172,11 @@ def card_statistics(child):
'title': _('Diaper change frequency')})
feedings = _feeding_statistics(child)
stats.append({
'type': 'duration',
'stat': feedings['btwn_average'],
'title': _('Feeding frequency')})
for item in feedings:
stats.append({
'type': 'duration',
'stat': item['btwn_average'],
'title': item['title']})
naps = _nap_statistics(child)
stats.append({
@ -235,22 +238,40 @@ def _feeding_statistics(child):
:param child: an instance of the Child model.
:returns: a dictionary of statistics.
"""
feedings = [
{
'start': timezone.now()-timezone.timedelta(days=3),
'title': _('Feeding frequency')+ " 3 "+_("days")
},
{
'start': timezone.now()-timezone.timedelta(weeks=2),
'title': _('Feeding frequency') + " 2 "+_("weeks")
},
{
'start': timezone.make_aware(datetime.combine(date.min, time(0,0)) + timezone.timedelta(days=1) ),
'title': _('Feeding frequency')
}
]
for timespan in feedings:
timespan['btwn_total'] = timezone.timedelta(0)
timespan['btwn_count'] = 0
timespan['btwn_average'] = 0.0
instances = models.Feeding.objects.filter(child=child).order_by('start')
feedings = {
'btwn_total': timezone.timedelta(0),
'btwn_count': instances.count() - 1,
'btwn_average': 0.0}
last_instance = None
for instance in instances:
if last_instance:
feedings['btwn_total'] += instance.start - last_instance.end
for timespan in feedings:
if last_instance.start > timespan['start']:
timespan['btwn_total'] += instance.start - last_instance.end
timespan['btwn_count'] += 1
last_instance = instance
if feedings['btwn_count'] > 0:
feedings['btwn_average'] = \
feedings['btwn_total'] / feedings['btwn_count']
for timespan in feedings:
if timespan['btwn_count'] > 0:
timespan['btwn_average'] = \
timespan['btwn_total'] / timespan['btwn_count']
return feedings