首页 > 解决方案 > Django - 如何在子模型中调用父函数

问题描述

我有一个带有外键(“目标”)的子模型,它与 Django 中的父模型(“项目”)相关。所以“项目”有很多“目标”。我的目标是将一个特定目标的数量除以项目的总量,由函数“total_budget”计算。因此,我试图在“目标”模型中调用函数“total_budget”。可能吗?这是最好的方法吗?

这是我的models.py代码:

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

在此先感谢您的帮助

标签: djangofunctionmodelparent-child

解决方案


您可以总结amount所有相关 Objectives的s :

from django.db.models import Sum

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

self对象在哪里Project


推荐阅读