如何从不同的模型访问模型字段?这可能吗?

How do I access a model field from a different model? is this possible at all?

假设我有两个模型

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 模型的项目模型访问 total_cost 以计算 percentage_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 对象没有属性 'project'

我是 django 的新手,现在才刚刚接触。非常感谢任何帮助

简单地说,您可以使用点表示法访问外键上的字段:

举个例子:

field_changer_order = FieldChangeOrder.objects.get(pk=1)
project_total_cost = field_changer_order.project.total_cost