Django Query how to sum returned objects method

Viewed 57

I have a model:

class TimeStamp(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    t_in = models.DateTimeField(_("In"), auto_now=False, auto_now_add=False)
    t_out = models.DateTimeField(
        _("Out"), auto_now=False, auto_now_add=False, blank=True, null=True)


    class Meta:
        verbose_name = _("TimeStamp")
        verbose_name_plural = _("TimeStamps")

    def __str__(self):
        return str(f'{self.t_in.date()} {self.user.get_full_name()}')

    def get_absolute_url(self):
        return reverse("TimeStamp_detail", kwargs={"pk": self.pk})

    def get_total_hrs(self):
        if self.t_out:
            t_hrs = abs(self.t_out-self.t_in).total_seconds()/3600
        else:
            t_hrs = '0'
        return str(t_hrs)

then in my views.py

def timeclock_view(request):
    week_start = timezone.now().date()
    week_start -= timedelta(days=(week_start.weekday()+1) % 7)
    week_end = week_start + timedelta(days=7)

    obj = request.user.timestamp_set.filter(
        t_in__gte=week_start, t_in__lt=week_end)



    obj.aggregate(total_hrs=Sum('get_total_hrs'))

    if obj:
        last = obj.last()
        context = {'obj': obj, 'last': last,
            'week_start': week_start, 'week_end': week_end, 'week_total': total_hrs, }
    else:
        context = {}
    return render(request, 'timeclock/timeclock_view.html', context)

How do i write this to get a sum of the hrs for the queryset? obj.aggregate(total_hrs=Sum('get_total_hrs)) is giving me an error:

django.core.exceptions.FieldError: Cannot resolve keyword 'get_total_hrs' into field. Choices are: description, id, note, note_set, pw, t_in, t_out, user, user_id

1 Answers

Aggregation is done on the database. That means you can use only fields in the aggregation, and not model functions or properties.

I would first implement the logic of get_total_hrs with an annotate() queryset, then use the this queryset to aggregate over the calculated field.

from django.db.models.functions import Abs
from django.db.models import F, ExpressionWrapper, DurationField, Sum

queryset.annotate(
    total_hrs=ExpressionWrapper(
        Abs(F("t_out") - F("t_in")), 
        output_field=DurationField()
    ),
).aggregate(overall_hrs=Sum("total_hrs"))
Related