如何从其他模型访问模型字段?这有可能吗?

时间:2019-11-12 20:23:43

标签: django python-3.x django-models django-model-field

假设我有两个模型

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还是很陌生,现在就刚开始涉猎。任何帮助都非常感激

1 个答案:

答案 0 :(得分:1)

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

例如:

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