【问题标题】:Reduce large number to intword in Django without editing template在不编辑模板的情况下将大量数字减少到 Django 中的 intword
【发布时间】:2018-12-25 13:49:39
【问题描述】:

我正在开发一个使用 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 %}

显示在相应列中的数字以原始格式显示,例如这 1000000000。我想让它更易于阅读。我找到了两种分离数千人的解决方案

我还看到有类似于intcomma 的东西,即intword,它会转换例如1000000 到 100 万,在我看来,这更具人类可读性。与intcomma 一样,这对我来说不是一个可行的解决方案,这就是为什么我正在寻找像USE_THOUSAND_SEPARATOR = True 这样的全局设置,但是将1000000 显示为100 万(或Mio。)而不是1,000,000。

【问题讨论】:

    标签: python django django-tables2


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多