An issue making addition through models.py making a simple calculation

Viewed 37

Hello guys im practicing on django by now developping a simple expense tracker for a main project expample: Buying a flippable car for X amount and adding all the other expenses to get a single total.

my operation is mainly done in my model.py

models.py

from django.db import models

# Create your models here.
class Project(models.Model):
    title = models.CharField(max_length=100)
    amount = models.FloatField()
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.title



class Expenses(models.Model):
    project = models.ForeignKey(Project, related_name='expenses', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    amount = models.FloatField()
    

    def __str__(self):
        return self.title

    
    def get_total_project_amount(self):
        return self.amount  + self.project.amount

What i wanna do is adding the main project and all the expenses togheter, but im not using the proper way, when i render the resuld it renders like this:

main project: 50$ expenses added from a model form : 2(new) expense: 13(new) expense: 25(new)

the total is: 52 total: 63 total: 75

I wanna render the main project and all the expenses to get a single result, something like 50+2+13+25 total : 90$ total amount soent to fix the car.

Anyone that understand addition lojic help please and thank you

.

1 Answers

You can sum upt the expenses with:

class Project(models.Model):
    # …
    
    @property    
    def total_amount(self):
        subtotal = self.expenses.aggregate(
            subtotal=Sum('amount')
        )['subtotal'] or 0
        return self.amount + subtotal

You can thus determine the total cost for a Project object myproject with:

myproject.total_amount

this will thus sum up the amount plus the sum of all the related Expenses.


Note: normally a Django model is given a singular name, so Expense instead of Expenses.


Note: When you make calculations with money, it is better to use a DecimalField [Django-doc], not a FloatField [Django-doc]. Floats can generate rounding errors when you perform calculations. You can also use django-money [GitHub] to specify a MoneyField. This has also specifies a currency, and can convert money to a different currency.

Related