D_P
D_P

Reputation: 862

How to get total sum based on the date__year?

Here in the template I am iterating MyModel objects. Now in the template I want to get the total sum of integer fields for the particular year.

I don't know how I can I use these three functions in order to get the total sum of field? Or there might be any better approach ?

model

class MyModel(models.Model):
    date = models.DateField()
    field1 = models.DecimalField(default=0.0)
    field2 = models.DecimalField(default=0.0)

views

def get_total_field1(year):
    return MyModel.objects.filter(date__year=year).annotate(total=Sum('field1'))['total']
   
def get_total_field2(year):
    return MyModel.objects.filter(date__year=year).annotate(total=Sum('field2'))['total']

def get_total(year):
    return get_total_field1() + get_total_field2()
   
   
class MyView(ListView):
   model = MyModel
   template_name = 'my_template.html'

       

template

{% for obj in objs %}
    <tr>
    <td>{{obj.date|date:'Y'}}</td>
    <td>Field 1 total sum for obj.date </td>
    <td>Field 2 total sum for obj.date</td>
    <td>Field 1 total + field2 total </td>
 {% endfor %}

Upvotes: 0

Views: 35

Answers (1)

Alex Paramonov
Alex Paramonov

Reputation: 2740

Templates are for displaying data. Calculations are more like business logic that should go to Python code. So my advice - calculate everything you need in the code (for "sum" see .annotate() Django method) and then just display pre-calculated variables in your templates.

In your example I would move "get_total_field1" and other methods into the model itself as property, then you can just do obj.get_total_field1 in your template.

Upvotes: 1

Related Questions