# mathematical operations between Model Fields

Hi,

I’m trying to build a swimming pool water test app as my first project but stumbled on a problem - I don’t know how to do mathematical operations between model fields. So, I have a function in models.py:

class PoolTest(models.Model):
location = models.CharField(max_length=50)
freecl = models.DecimalField(max_digits=5, decimal_places=2)
totalcl = models.DecimalField(max_digits=5, decimal_places=2)

Then I want to display it in .html file with:

Location: {{ pooltest.location }}<br>
Free Cl: {{ pooltest.freecl }}<br>
Total Cl: {{ pooltest.totalcl }}<br>

But I also need to show Combined Cl after Total Cl:, which is Combined Cl = Total Cl - Free Cl

How can I get it done, please?

Updated: There is my views.py

from django.shortcuts import render
from pooltest.models import PoolTest

def pooltest(request):
all_pooltests = PoolTest.objects.all()
return render(request, 'pooltest/home.html', {'all_pooltests':all_pooltests})

(Can’t be more specific without seeing your view.)

I tried that, but it didn’t work, obviously I used wrong syntax… I updated topic with my view.py file.
What would be correct way to do it?

Thank you,

Ok, so what you’re looking for is to calculate this “combined Cl” for each row in your table.

The function you’re looking for is the annotate function.

In this case, you could do something like this:

all_pooltests = PoolTest.objects.annotate(combined_cl = F('totalcl') - F('freecl'))

You will then be able to reference that annotated field in your template as pooltest.combined_cl

If you need to perform more complex calculations in your query, Django supports a set of database functions that can also be used.

Ken

Works, thank you!