在不编辑模板的情况下将大数减少为Django中的整数

时间:2018-12-25 13:49:40

标签: python django django-tables2

我正在开发一个使用django,django-tables2和Bootstrap4显示html表的Web应用程序。我有一列AUM,其中包含非常大的数字(最多十亿)。在我的models.py中,相应的模型为models.Interfield()使用了AUM

class MyModel(models.Model):
    ...
    AUM = models.IntegerField(null= True, blank= True)
    ...

使用django-tables2和Bootstrap4将该模型转换为表格并使用

呈现为模板
{% render_table table %}

在相应列a中显示的数字以原始格式显示,例如这十亿。我想让它更易读。我发现了两种解决方案,可以分开数千个

  • 使用intcomma中的django.contrib.humanize对我来说不是一个可行的解决方案,因为它需要我在模板中添加一个过滤器,而我只是添加{% render_table table %}({ {3}})
  • 在我的USE_THOUSAND_SEPARATOR = True中使用全局设置settings.py,这对我来说很有效(JEP 307: Parallel Full GC for G1

我还看到有一个类似于intcomma的东西intword,它可以转换例如我认为1000000变成1百万甚至更容易被人理解。与intcomma一样,这对我来说不是一个可行的解决方案,这就是为什么我要寻找USE_THOUSAND_SEPARATOR = True这样的全局设置,但是却要显示1000000为1百万(或Mio.)而不是1,000,000。

1 个答案:

答案 0 :(得分:0)

Django-tables2允许使用TemplateColumn来为单元格使用django模板语言。这确实需要您创建自定义表:

# settings.py

INSTALLED_APPS = (
    # ...
    "django.contrib.humanize",
    "django_tables2"
    # ...
)


# tables.py

import django_tables2 as tables


class MyTable(tables.Table):
    AUM = tables.TemplateColumn(
        template_code="{% load humanize %}{{ value | intword }}"
    )

    class Meta:
        model = MyModel
        sequence = ("AUM", "...")  # using "..." here will automatically add the remaining columns of the model to the table.

# views.py

class MyView(SingleTableView):
    table_class = MyTable