使用Django模板过滤器进行数学运算?

dev*_*eng 1 python django templates filter

在我的数据库中,我有一个存储价格信息的整数字段,如"10399","84700".显示时,它们应为"$ 103.99"和"$ 847.00".

我需要显示int*0.01.

我想知道是否有办法使用Django模板过滤器?喜欢:

{{ item.price|int_to_float_and_times_0.01 }}
Run Code Online (Sandbox Code Playgroud)

另一个问题,实际上我选择了整数,因为我认为它比在数据库中使用float更有效.真的吗?

rya*_*how 7

您可以创建自己的模板过滤器,只需将输入除以100即可完成所需的操作.例如:

在my_app/templatetags/currency_helper.py中:

from django import template
register = template.Library()

@register.filter
def to_currency(value):
    return float(value) / 100.0
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中:

{% load currency_helper %}

etc...

{{item.price|to_currency}}
Run Code Online (Sandbox Code Playgroud)

此外,如果我是你,我会将货币值存储在您的数据库中作为十进制字段,以避免这样做或处理舍入错误的头痛.