如何在Django中以集中方式使用floatformat

3 投票
3 回答
2263 浏览
提问于 2025-04-16 06:34

在我的项目中,我需要用户提供一些测量值、价格和重量。我想把这些数据存储为两位小数的格式。我觉得应该用DecimalField,而不是FloatField,因为我不需要太高的精度。

当我在模板中打印这些数值时,我不想显示那些没有意义的零小数位。

举个例子:

10.00 应该只显示 10

10.05 应该显示 10.05

我不想在每个显示这个数值的模板中都使用floatformat过滤器,太麻烦了。所以我在想有没有什么办法可以集中处理,让整个应用程序都能统一显示这些值。

谢谢

3 个回答

0

在模型中添加一个属性,像这样:

_weight = models.DecimalField(...)
weight = property(get_weight)

def get_weight(self):
    if self._weight.is_integer():
        weight = int(self._weight)
    else:
        weight = self._weight
    return weight
2

你试过django的插件Humanize吗?

你可能会在那找到你想要的东西。

编辑

你说得对,humanize 过滤器在这里不管用。经过查找django自带的过滤器和标签,我没有找到能解决你问题的东西。所以,我觉得你需要一个自定义的过滤器。类似于...

from django import template

register = template.Library()

def my_format(value):
    if value - int(value) != 0:
        return value
    return int(value)

register.filter('my_format',my_format)
my_format.is_safe = True

然后在你的django模板中,你可以这样做...

{% load my_filters %}
<html>
<body>
{{x|my_format}}
<br/>
{{y|my_format}}
</body>
</html>

对于值xy,分别是1.01.1,这样会显示:

  1
  1.1

希望这能帮到你。

1

我终于找到了这个问题的答案,并把它发在了我的博客上:

http://tothinkornottothink.com/post/2156476872/django-positivenormalizeddecimalfield

希望有人觉得这个内容有用。

撰写回答