From 4037f97e72bcac3d7322fb3d1ddcf291fbeb2ed3 Mon Sep 17 00:00:00 2001 From: Christopher Charbonneau Wells Date: Sat, 4 Nov 2017 12:51:49 -0400 Subject: [PATCH] Add a NapManager to Sleep model and use it on the naps card. --- core/models.py | 9 ++++++++- dashboard/templatetags/cards.py | 23 +++-------------------- 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/core/models.py b/core/models.py index aac813c2..8a4e00b4 100644 --- a/core/models.py +++ b/core/models.py @@ -174,6 +174,12 @@ class Note(models.Model): return 'Note' +class NapsManager(models.Manager): + def get_queryset(self): + qs = super(NapsManager, self).get_queryset() + return qs.filter(id__in=[obj.id for obj in qs if obj.nap]) + + class Sleep(models.Model): model_name = 'sleep' child = models.ForeignKey('Child', related_name='sleep') @@ -182,6 +188,7 @@ class Sleep(models.Model): duration = models.DurationField(null=True, editable=False) objects = models.Manager() + naps = NapsManager() class Meta: default_permissions = ('view', 'add', 'change', 'delete') @@ -191,8 +198,8 @@ class Sleep(models.Model): def __str__(self): return 'Sleep' + @property def nap(self): - # TODO: Add a way to filter naps from Sleep.objects() easily. nap_start_min = timezone.datetime.strptime( settings.BABY_BUDDY['NAP_START_MIN'], '%H:%M').time() nap_start_max = timezone.datetime.strptime( diff --git a/dashboard/templatetags/cards.py b/dashboard/templatetags/cards.py index 9a3c5276..ecefa592 100644 --- a/dashboard/templatetags/cards.py +++ b/dashboard/templatetags/cards.py @@ -2,7 +2,6 @@ from __future__ import unicode_literals from django import template -from django.conf import settings from django.db.models import Sum from django.utils import timezone @@ -197,28 +196,12 @@ def card_sleep_naps_day(child, date=None): specific date. :param child: an instance of the Child model. :param date: a Date object for the day to filter. - :returns: a dictionary of nap data statistics and the nap bounds. + :returns: a dictionary of nap data statistics. """ - nap_start_min = timezone.datetime.strptime( - settings.BABY_BUDDY['NAP_START_MIN'], '%H:%M').time() - nap_start_max = timezone.datetime.strptime( - settings.BABY_BUDDY['NAP_START_MAX'], '%H:%M').time() - - local = timezone.localtime(date) - start_lower = local.replace( - hour=nap_start_min.hour, - minute=nap_start_min.minute, - second=0).astimezone(timezone.utc) - start_upper = local.replace( - hour=nap_start_max.hour, - minute=nap_start_max.minute, - second=0).astimezone(timezone.utc) - instances = Sleep.objects.filter(child=child) \ - .filter(start__gte=start_lower, start__lte=start_upper) + date = timezone.localtime(date).astimezone(timezone.utc) + instances = Sleep.naps.filter(child=child, start__date=date) return { 'type': 'sleep', - 'min_time': nap_start_min, - 'max_time': nap_start_max, 'total': instances.aggregate(Sum('duration')), 'count': len(instances)}