试图截断 django_table2 中的列内容

trying to truncate column content in django_table2

我有一个 django table,其列的小数点最多为 7 点。该列称为错误。谁能帮我将数据截断到小数点后两位或四舍五入?

型号:

class Course (models.Model):
    null_value = 0
    department = models.CharField(max_length=200)
    course = models.CharField(max_length=200)
    semester = models.CharField(max_length=200)
    actual = models.FloatField (default=0)
    prediction = models.FloatField(default=0)
    error = models.FloatField(default=0)

table

class NameTable(tables.Table):
    # actions = tables.Column(orderable=False)
    # selection = tables.CheckBoxColumn(accessors="pk", orderable = False)
    # table = n_object.filter(course=course_selected).order_by('id').all()
    table=tables.Table
    # actual1 = table.values_list('actual')

    error = tables.Column(verbose_name='ERROR (%)')
    class Meta:
        model = Course
        fields = ("semester","actual","prediction","error")
        order_by_field = True

视图中的内容(我将其修改为你们需要的):

def report_table1(request):
    n_object = Department.objects.all()
    table = n_object.filter(department=department_selected).order_by('id').all()
    t_data = NameTable(table)
    RequestConfig(request).configure(t_data)

    return render(request, 'table.html', {"table_course": t_data})

html 文件

{% block content %}
{% load render_table from django_tables2 %}

<div style="text-align: center;">
    <!--<h2>Prediction for all Courses</h2>-->
    <!--<table style="width: 100%;" "text-align:center;">-->

    {% render_table table_course%}
    <!--</table>-->

{% endblock %}

我该怎么办?我希望将错误列中的数字四舍五入

这是一个简单的解决方案,您可以使用一个简单的技巧来舍入您的数据。您应该在模型中创建一个 属性 来定义错误记录的舍入值。让我们看看代码(它应该可以工作,但我现在无法测试):

型号:

class Course (models.Model):
    null_value = 0
    department = models.CharField(max_length=200)
    course = models.CharField(max_length=200)
    semester = models.CharField(max_length=200)
    actual = models.FloatField (default=0)
    prediction = models.FloatField(default=0)
    error = models.FloatField(default=0)

    @property
    def roundedError(self):
        return u"%.2f" % (self.error)
        # or you can return like ruddra's answer ;)
        # return round(self.error, 2)

Table:

class NameTable(tables.Table):
    ...
    roundedError = tables.Column()

您可以使用的另一个解决方案:

class NameTable(tables.Table):

     def render_error(self, **kwargs):
        return round(kwargs['value'], 2)
        # or you can return like markdesign's answer :) 
        #return u"%.2f" % (kwargs['value'])  

     class Meta:
        model = Course
        fields = ("semester","actual","prediction","error")
        order_by_field = True