Django - how to call a parent function in a child model

Viewed 201

I have a child model with a Foreignkey ("Objective"), that related to a parent model ("Project") in Django. So the "Project" has many "Objectives". My goal is to divide the amount of one particular objective to the total amount of the Project, computed by the function "total_budget". Hence, I am trying to call the function "total_budget" in the "Objective" model. Is it possible? Is that the best way to do it?

Here is my models.py code:

class Project(models.Model):
    model_name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True, blank=True)
    current_savings = models.IntegerField()
    monthly_salary = models.IntegerField()
    monthly_savings = models.IntegerField()
    horizon = models.DateField(default='2025-12-31')

    def save(self, *args, **kwargs):
        self.slug = slugify(self.model_name)
        super(Project, self).save(*args, **kwargs)

    def total_budget(self):
        #define current date and horizon to compute the number of months until horizon
        curr_date = datetime.date.today()
        horizon = self.horizon
        dates = [curr_date.strftime('%Y-%m-%d'), horizon.strftime('%Y-%m-%d')]
        start, end = [datetime.datetime.strptime(_,'%Y-%m-%d') for _ in dates]
        re_mon = (end. year - start. year) * 12 + (end. month - start. month)

        #budget is equal to the monthly savings times remaining months, plus current savings
        budget = self.monthly_savings*re_mon + self.current_savings

        return budget



    class Objective(models.Model):
        project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='objectives')
        title = models.CharField(max_length=100)
        amount = models.DecimalField(max_digits=8, decimal_places=0)
        expiration = models.DateField()
        isexpensed = models.BooleanField()
        investable = models.BooleanField()
    
        class Meta:
            ordering = ('expiration',)
    
        def pct_totalbudget(self):
            project = Project
    
    
    
            return absamount

Thanks in advance for your help

1 Answers

You can sum up the amounts of all related Objectives with:

from django.db.models import Sum

self.objectives.aggregate(
    total_amount=Sum('amount')
)['total_amount'] or 0

where self is the Project object.

Related