Django 模板过滤器:将 floatformat 应用于 widthratio

cod*_*nce 2 django django-templates

widthformat 自动四舍五入。但是,如果可能,我想在模板标记中执行除法并四舍五入到 n 位小数。例如:

    <h4>Strike Rate: {% widthratio selected_replies user.projectreply_set.count 100 %}</h4>
Run Code Online (Sandbox Code Playgroud)

目前它返回一个整数。

我将如何在此处应用 floatformat,或者我是否需要在视图中执行此工作?

使用模型的替代方法

class UserProfile(models.Model):
    ....
    ....
    def get_strike_rate(self):
        selected_replies = self.user.projectreply_set.filter(is_selected_answer=True).count()
        my_replies = self.user.projectreply_set.count()
        if my_replies >0:
             return round((selected_replies/my_replies)*100.0,2)
        else:
             return 0
Run Code Online (Sandbox Code Playgroud)

nev*_*ner 5

据我所知,没有标准的 Django 过滤器。但是您几乎没有其他选择。首先是正如你所说的在视图中做数学。另一种是使用自定义模板过滤器

from django import template
register = template.Library()

@register.filter
def div(value, div):
    return round((value / div) * 100, 2)
Run Code Online (Sandbox Code Playgroud)

在模板中,您可以这样使用它:

{{ a|div:b }}
Run Code Online (Sandbox Code Playgroud)

第三个选项如果您使用的是 Django 1.8 并且更少的是django-mathfilters,您可以尝试使用它的 div 和 mult 过滤器以及 Django floatformat过滤器的组合。