Search code examples
djangodjango-viewsdjango-generic-views

Math in Django to get a total returned


I'm trying to get to a result that tells me something like 10.5 hours worked on a project.

here's what I'm doing in my view:

time = Time.objects.filter(my_company=my_company, project=project)
raw_hours = time.aggregate(Sum('hours'))
raw_minutes = time.aggregate(Sum('minutes'))
adj_minutes = raw_minutes.raw_minutes__sum / 100
hours = adj_minutes + raw_hours.raw_hours__sum
return {'hours': hours}

When I add {{ view.hours }} to my template, I'm not seeing anything in the return. I'm expecting view.hours == 10.5 or something like that depending on the math.

So I have two questions. Am I thinking about this correctly and is there a more efficient way to do this?

Thanks for you help.


Solution

  • You can get both aggregates by doing:

    d = time.aggregate(Sum('hours'), Sum('minutes'))
    

    this should return a dictionary that looks like this:

    {'hours__sum' : Decimal('10'), 'minutes__sum' : Decimal('630')}
    

    so to access the values you should deal with it the same way as you deal with any other dictionary.

    hours = d['hours__sum']
    

    On the template, you only need to provide the key for the context dictionary, in your case:

    {{ hours }}