首页 > 解决方案 > 如何在 django models.py 中编写一个使用定义的函数?

问题描述

我在 models.py 中写了一个函数来计算百分比。但它没有显示计算值。

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

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 }} 来查看它以及实际价格。请给我一个方法。

标签: djangodjango-models

解决方案


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

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

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


推荐阅读