使用 django-tables2 时如何格式化浮点数的显示?



我正在使用django-tables2来显示一些数据。我有一列浮点数,并希望它们仅显示小数点后两位(因此,10.238324将显示为10.24)。有没有简单的方法可以做到这一点?在 Django 模板中,我使用{{number||floatformat:2}}来做到这一点。

潜在相关文档:
http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html。

如果只有一列包含浮点数,请在render_<column_name>()方法中设置值的格式:

class NumberTable(tables.Table):
number = tables.Column()
def render_number(self, value):
return '{:0.2f}'.format(value)

如果您有多个带有浮点数的列,则可以定义自定义列并重复使用它:

class NumberColumn(tables.Column):
def render(self, value):
return '{:0.2f}'.format(value)

class NumberTable(tables.Table):
temperature = NumberColumn()
pressure = NumberColumn()
flow = NumberColumn()

此自定义列还可能实现一个自定义构造函数,添加小数位数(如果要更改)。

1. 在视图中舍入数据

实际上,这并不直接控制数字的显示,并且会省略不需要它们的值的小数(24.1而不是24.10)。这是一个快速的解决方案,因为这是你自己的观点,你必须修改。然而,这不是一个好的风格。

2. 替换django_tables2渲染的模板

文档说您可以使用自己的表格模板

默认模板(源代码)包含可以覆盖的块。我认为这是要走的路。您自己的float_table.html可能类似于以下示例:

{% extends "table.html" %} {# hope that finds the original template #}
{% block table.tbody.row %}
<tr {{ row.attrs.as_html }}>
{% for column, cell in row.items %}
<td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell|floatformat:2 }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
{% endfor %}
</tr>
{% endblock table.tbody.row %}

这会将floatformat筛选器应用于未定义 localize 属性的每个列。如果您不想在格式上更加个性化,则可以渲染每个单元格,这似乎是获得所需内容的最不侵入性的方式。

如果你想要更精细的粒度,那就更难了。我认为高级模块的微调很少是美丽的:)

3. 通过 javascript 添加<td><tr>属性和格式

只是为了完整起见,也不是我推荐的方式:文档告诉您如何将自定义属性添加到行或列。你可以用它作为一个钩子来添加一个类,比如float2。通过javascript(也许也通过CSS?),你可以对渲染的内容进行舍入。


所以我认为选项 2 确实是最干净的方法。您甚至可以简化模板代码段,以便在您不感兴趣时不检查本地化。

我认为对于django_tables2来说,有一个钩子将模板过滤器链接到单元格的内容将是一个很好的功能。也许您向他们发送功能请求:)

你也可以使用normalize

class DecimalColumn(tables.Column):
'''Column to normalize decimals'''
def render(self, value):
return value.normalize()

用法:

class MyTable(tables.Table):
amount = DecimalColumn()

最新更新