Django模型:两个字段的相乘

时间:2018-07-30 04:53:36

标签: django django-models django-templates

我想将模型中的两个字段相乘并将其显示在模板中。我有两种型号:

class Priority(models.Model):
    priorityName=models.CharField(max_length=100)
    priorityScore=models.IntegerField()
    def __str__(self):
        return str(self.priorityScore)

class ImpactMatrix(models.Model):
    objectName=models.ForeignKey(ObjectName,on_delete=models.CASCADE)
    actionName=models.ForeignKey(ActionObject,on_delete=models.CASCADE)
    priority=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='priority')
    functional=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='functional')
    supervision=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='supervision')
    approval=models.ForeignKey(Priority,on_delete=models.CASCADE,related_name='approval')

我想在ImpactMatrix.priority * ImpactMatrix.functional中乘以priorityScore

我该怎么做?

2 个答案:

答案 0 :(得分:3)

在模型中定义@property,并像其他任何模型字段一样从模板访问它,

class ImpactMatrix(models.Model):
    objectName = models.ForeignKey(ObjectName, on_delete=models.CASCADE)
    actionName = models.ForeignKey(ActionObject, on_delete=models.CASCADE)
    priority = models.ForeignKey(Priority, on_delete=models.CASCADE, related_name='priority')
    functional = models.ForeignKey(Priority, on_delete=models.CASCADE, related_name='functional')
    supervision = models.ForeignKey(Priority, on_delete=models.CASCADE, related_name='supervision')
    approval = models.ForeignKey(Priority, on_delete=models.CASCADE, related_name='approval')

    @property
    def some_name(self):
        return self.priority.priorityScore*self.functional.priorityScore

和你的脾气,

{% impactmatrix_object.some_name %}

答案 1 :(得分:1)

您需要使用自定义模板标签。

您可以参考link以获得有关自定义模板标签的更多信息

@register.simple_tag()
def multiply(priority, functional, *args, **kwargs):
    return priority * functional

您可以在模板中添加这样的标签

{% load your_custom_template_tags %}
{% multiply im_obj.priority.priorityScore  im_obj.functional.priorityScore %}