-2

假设我有两个模型

class Project(models.Model):
    project_number = models.Charfield(primary_key=True, max_length=10)
    project_title = models.Charfield(max_length=100)
    total_cost = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)

class FieldChangeOrder(models.Model):
    project = models.FoereignKey('Project', on_delete=models.CASCADE)
    funding_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    percentage_of_funding = ( funding_amount / total_cost ) * 100

如何从 FieldChangeOrder 模型访问 Project 模型中的 total_cost 以计算 percent_of_fundiing 字段的值?

我尝试了以下

class Project(models.Model):
    project_number = models.Charfield(primary_key=True, max_length=10)
    project_title = models.Charfield(max_length=100)
    total_cost = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)

class FieldChangeOrder(models.Model):
    project = models.FoereignKey('Project', on_delete=models.CASCADE)
    funding_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)

    @property
    def percentage_of_funding(self):
        return (self.funding_amount/self.project.total_cost) * 100

但是 ^ 错误说 FieldChangeOrder 对象没有属性“项目”

我对 django 还很陌生,现在只是在涉足。任何帮助深表感谢

4

1 回答 1

1

简单地说,您可以使用点符号来访问外键上的字段:

举个例子:

field_changer_order = FieldChangeOrder.objects.get(pk=1)
project_total_cost = field_changer_order.project.total_cost
于 2019-11-12T20:32:16.193 回答