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})

In your view that is generating your context being rendered, you can add another variable that is then included in your template.

(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!
I will definitely read more about database functions.

hello, i am new to django and i am enjoying it. i needhelp with a trivial problem- i have a django model with items that have unit_price and quantity and total. i want the total to be calculated automatically on the admin site after i insert the unit_price and the quantity. how to implement

Welcome @b0nafideCicer0 !

Are you talking about changing it on the page before saving those values? Or are you talking about clicking “save” and having that process update what’s shown on the page?