为了账号安全,请及时绑定邮箱和手机立即绑定

在 Django 中将大量减少到 intword 而不编辑模板

在 Django 中将大量减少到 intword 而不编辑模板

慕莱坞森 2021-09-25 16:33:43
我正在开发一个使用 django、django-tables2 和 Bootstrap4 显示 html 表的 Web 应用程序。我有一列AUM包含非常大的数字(高达数十亿)。在我models.py的相应模型中使用models.Interfield()for AUM。class MyModel(models.Model):    ...    AUM = models.IntegerField(null= True, blank= True)    ...使用 django-tables2 和 Bootstrap4,这个模型被转换成一个表格并使用{% render_table table %}显示在相应列 a 中的数字以原始格式显示,例如这个 1000000000。我想让它更易读。我找到了两个用于分隔数千个的解决方案使用intcommafrom django.contrib.humanizewhich 对我来说不是一个可行的解决方案,因为它需要我在模板中添加一个过滤器,而我只是添加{% render_table table %}(https://docs.djangoproject.com/en/2.1/ref/contrib/humanize / )USE_THOUSAND_SEPARATOR = True在 my 中使用全局设置,settings.py这是一个对我有用的解决方案(https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#use-thousand-separator)我也看到有类似的东西intcomma它intword并把它转换例如百万到1万元,在我看来更是人类可读的。如同intcomma这不是我一个可行的解决方案,这就是为什么我要寻找一个全局设置类似USE_THOUSAND_SEPARATOR = True但是显示百万为1万美元(或Mio.)不1,000,000。
查看完整描述

1 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

Django-tables2 允许使用 aTemplateColumn为单元格使用 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


查看完整回答
反对 回复 2021-09-25
  • 1 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信