如何在django models.py中编写使用定义的函数?

时间:2019-04-25 07:26:53

标签: django django-models

我在models.py中编写了一个函数,该函数将计算百分比。但是它没有显示计算出的值。

我在models.py中编写了一个名为“ cal_amount”的函数来执行计算。将值返回到模型字段。但是当我打电话时它显示为None。

class Course(models.Model):
        price = models.FloatField("Price", blank=True, null=True)
        voucher_id = models.CharField(max_length=255,blank=True, null=True)
        voucher_amount = models.IntegerField(blank=True, null=True)
        discounted_amount = models.IntegerField(blank=True, null=True)
        def __str__(self):  
            return self.course_name

        def cal_amount(self):
             self.discounted_amount = (self.voucher_amount/100)*self.price
             return self.discounted_amount

我想要的是计算出的金额,要存储在Discounted_amount中。因此我可以在html中使用{{obj.discounted_amount}}来查看它以及实际价格。请给我建议一种方法。

1 个答案:

答案 0 :(得分:0)

您可以使用属性代替模型中的字段。

class Course(models.Model):
        price = models.FloatField("Price", blank=True, null=True)
        voucher_id = models.CharField(max_length=255,blank=True, null=True)
        voucher_amount = models.IntegerField(blank=True, null=True)

        def __str__(self):  
            return self.course_name

        @property
        def discounted_amount(self):
             return (self.voucher_amount/100)*self.price


course = Course.objects.get(id=1)
course.discounted_amount # returns the calculated discount

请记住,您将整数与浮点数混合在一起进行计算

相关问题