diff --git a/castellum/recruitment/templatetags/appointments.py b/castellum/recruitment/templatetags/appointments.py index 4b62df054612dba85066c6c7c3cfceedecef391f..9651c038988108a27f7127e5a5adfbb870e8117c 100644 --- a/castellum/recruitment/templatetags/appointments.py +++ b/castellum/recruitment/templatetags/appointments.py @@ -29,8 +29,6 @@ register = template.Library() @register.filter def showup_level(subject): - subject.annotate_showup_stats() - if subject.showup_score > 6: return 'danger' elif subject.showup_score > 2: @@ -41,8 +39,6 @@ def showup_level(subject): @register.filter def showup_summary(subject): - subject.annotate_showup_stats() - labelled = [] for status, label in Appointment.SHOWUP_CHOICES: count = getattr(subject, 'showup_%i' % status) diff --git a/castellum/subjects/models.py b/castellum/subjects/models.py index e3994b3bde93d9ccbc9b31c1bd2b657d700179c4..5d641cb16fe8353d7c390ee97428f4eb4c17b201 100644 --- a/castellum/subjects/models.py +++ b/castellum/subjects/models.py @@ -30,6 +30,7 @@ from django.utils.translation import gettext_lazy as _ from dateutil.relativedelta import relativedelta from castellum.studies.models import StudyType +from castellum.utils import annotate_instance from castellum.utils import uuid_str from castellum.utils.fields import DateTimeField from castellum.utils.fields import RestrictedFileField @@ -257,17 +258,12 @@ class Subject(TimeStampedModel): else: return self.get_next_available_datetime(now) - def annotate_showup_stats(self): - from castellum.recruitment.models import Appointment - - if hasattr(self, 'showup_score'): - return - - annotated = Subject.objects.annotate_showup().get(pk=self.pk) - self.showup_score = annotated.showup_score - for status, label in Appointment.SHOWUP_CHOICES: - key = 'showup_%i' % status - setattr(self, key, getattr(annotated, key)) + def __getattr__(self, key): + if key.startswith('showup_'): + values = annotate_instance(self, Subject.objects.annotate_showup()) + return values[key] + else: + return super().__getattribute__(key) class SubjectNote(models.Model): diff --git a/castellum/utils/__init__.py b/castellum/utils/__init__.py index 056b88a26b71c8016b3a3b665bac7c2a724408b5..f13e4c6db9acdb190d1d161ca6a8e77e756322a0 100644 --- a/castellum/utils/__init__.py +++ b/castellum/utils/__init__.py @@ -63,3 +63,10 @@ def add_working_days(dt, days): else: dt += timezone.timedelta(days=1) return dt + + +def annotate_instance(instance, queryset, force=False): + keys = list(queryset.query.annotations.keys()) + values = queryset.values(*keys).get(pk=instance.pk) + instance.__dict__.update(values) + return values