[Django]-Summing up values from database in DJANGO template

4👍

You could write your own template filter for this. Create a new python file called ‘grade_filters.py’ in a folder called ‘templatetags’ in your template folder and declare a new templatetag as follows:

from django import template

register = template.Library()

def grade_to_number(grade):
    map_dict = {'A+': 10, 'A':9, 'A-':8}
    if grade in map_dict:
        return map_dict[grade]
    else:
        return 0


@register.filter(name='sum_of_grades')
def return_item(grade_list):

    new_grades_list = [grade_to_number(grade) for grade in grade_list]
    try:
        return sum(new_grades_list)
    except:
        return 0

@register.filter(name='get_list_for_student')
def return_item(student_list, name):

    return student_list.filter(name=name)

Now, in your template you can load the new templatetag with

{% load grade_filters %}

Calculate the grade total of one student with:

{{ gradelist|get_list_for_student:'John'|sum_of_grades }}

2👍

It’s by design that you can’t do that in the templates. The django philosophy is such that logic of that sort belongs in the views.

We see a template system as a tool that controls presentation and presentation-related logic – and that’s it. The template system shouldn’t support functionality that goes beyond this basic goal.

source: https://docs.djangoproject.com/en/dev/misc/design-philosophies/#separate-logic-from-presentation

Though they do allow you to break the tools and write custom tags and filters like alexcxe said, it’s undoubtedly easier to just to include this sort of logic in your views and pass it as a context variable. I don’t know what your models look like, but a dict or a tuple would be fitting in this situation. I’ve had to do both in similar situations. If you provide more details, I can give you a specific implementation.

Every now and then it’s ok to break the rules, but im gathering that you’re new to django, so at this point, until you know when it’s ok, i’d suggest following the rules set by the django community, especially if your goal is to work with other django developers.

Leave a comment