django - 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
在此先感谢您的帮助
解决方案
您可以总结amount
所有相关 Objectives
的s :
from django.db.models import Sum
self.objectives.aggregate(
total_amount=Sum('amount')
)['total_amount'] or 0
self
对象在哪里Project
。
推荐阅读
- p5.js - 如何显示图像 3 秒
- c# - 从 FileResult 处理程序(操作)以 ajax 显示图像
- mongoose - Mongoose 查找并保存,希望将错误消息作为 res.json 发送
- scala - 如何在 Spark 中使用 Scala 从数据框中的单元格中提取表信息
- python-3.x - LinearSVC 参数贝叶斯优化
- django - Django下使用静态文件配置Nginx
- javascript - 在 React/Redux 应用程序中刷新页面后如何保持登录状态
- javascript - SetInterval 只运行一次
- ruby - 如何干净地对控制流方法进行单元测试
- linker - ENTRY(symbol) 命令是否总是将指令放在 .text 部分开头的符号处?