[Django]-How to do math operations in django template?

5πŸ‘

βœ…

(A similar question here.)

Good way to accomplish this seems to be to use django-mathfilters. This enables you to perform other math operations in addition to subtraction (add, multiply, divide, absolute value, etc.).

For your problem, this should work:
{{ object.var1|sub:object.var2 }}

If you know you will only ever need subtraction, you may find a simpler solution (though I don’t think it’s worth worrying about).

5πŸ‘

Its recommended to use either django view or models to do this kind of math operation. Because django template is used as presentation, and should not have any business logic or calculations. You can simply do the calculation using annotations in queryset. For example:

from django.db.models import F
object_list = ModelClass.objects.all().annotate(difference=F('var1') - F('var2'))

If you are using a Generic Display Views, then put this code in get_queryset like this:

class YourListView(ListView):
  ...

  def get_queryset(self, *args, **kwargs):
     qset = super(YourListView, self).get_queryset(*args, **kwargs)
     return qset.annotate(difference=F('var1') - F('var2'))

Then use it template like this:

{% for object in object_list %}
      {{ obj.difference }}
{% endfor %}
πŸ‘€ruddra

Leave a comment