django - 如何在 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 }} 来查看它以及实际价格。请给我一个方法。
解决方案
您可以使用属性来代替模型中的字段。
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
请记住,您将整数与浮点数混合以进行计算
推荐阅读
- asp.net-core - ASP.NET Core - 从 WebApi 提供静态内容
- php - 我似乎无法让我的联系表单在 HTML/PHP 中工作(PHP 新手并且完全卡住了)
- python - 检查多个变量是否为空,只替换那些为空的
- python - 在 Python VSCode 扩展上排序导入失败
- python - 如何在 Jupyter Notebooks 中使用常规的 VSCode Find?
- elasticsearch - Beats 无法访问弹性服务
- node.js - Nodemailer 错误:验证电子邮件不起作用
- r - 使用R中的for循环减去两个嵌套的数组列表
- linear-programming - 为什么 Microsoft Solver Foundation 不返回解决方案?
- javascript - React - 用玩笑测试倒计时组件(使用 setInterval 时如何在玩笑中等待 1 秒)