我如何计算 Django 中两个表的百分比

How do I calculate percentages from two tables in Django

m pretty new to the Django Framework and I am stuck at calculating a percentage. Here的问题是:

我有两个表 SocialCase 和 Donation:

class社会案例(models.Model):

title = models.CharField(max_length=200)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
organizer = models.TextField(max_length=200, null=True, blank=False)
description = models.TextField(null=True, blank=False)
created = models.DateTimeField(auto_now_add=True)
profile_image = models.ImageField(upload_to='static/images/')
case_tags = models.ManyToManyField('events.Tag')
target_donation = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)

class 捐款(models.Model):

user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
social_case = models.ForeignKey(SocialCase, on_delete=models.CASCADE)
raised = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)

我想使用@属性 方法来计算 raisedtarget_donation[ 之间的百分比=14=]

  1. target_donation字段表示需要的总金额 这个社会案例。 target_donation 将在 社交案例已创建。
  2. raised字段表示已经筹到的金额 目前提出。 raised 字段将是一个动态值, 将随着每次捐赠而增加

我想计算 SocialCase 模型的百分比。 我如何从 Donations 模型中引入 raised 列以计算每个社会案例的百分比并将其输出到 HTML 模板中?

非常感谢,抱歉,如果这是一个简单的问题,我m still a newbie and couldn在 Django 文档中找不到任何内容。

亲切的问候, 塞尔吉乌

当您定义 ForeignKey 时,它会在相关对象上创建一个“反向”字段。您可以使用 related_name 命名它,否则它默认为 <modelname>_set(模型名称小写)。在这种情况下,donation_set

这可能就是您所缺少的。代码将类似于

@property
def percent_raised(self):

    total = 0.0
    for donation in self.donation_set.all():
        total += float( donation.raised)

    return total / float( self.target_donation) * 100.0

在这种情况下,使用聚合函数计算 DB 查询中的捐款总和效率更高,但通用性要差得多。请参阅 the cheat sheet here(使用 Avg 的第三个示例,但在这种情况下,您需要 Sum 而不是 Avg