小编典典

django模板系统,在模型内部调用函数

django

我想从我的模型中的模板调用一个函数,例如:

class ChannelStatus(models.Model):
 ..............................
 ..............................

    def get_related_deltas(self,epk):
        mystring = ""
        if not self.get_error_code_delta(epk):
            return mystring
        else:
            for i in self.get_listof_outage():
                item = i.error_code.all()
                for x in item:
                    if epk == x.id:
                        mystring= mystring +" "+str(i.delta())
        return mystring 

当我想从模板中调用它时:假设在渲染时,我将channel_status_list传递为

channel_status_list = ChannelStatus.objects.all()

{% for i in channel_status_list %}
  {{ i.get_related_deltas(3) }}
{% endfor %}

这是行不通的,我能够调用一个不消耗任何东西的函数,但是如果找到有参数的函数就无法找到该怎么做


阅读 1211

收藏
2020-03-27

共1个答案

小编典典

你无法使用模板中的参数调用函数。你只能在视图中执行此操作。另外,你可以编写一个自定义模板过滤器,看起来可能像这样:

@register.filter
def related_deltas(obj, epk):
    return obj.get_related_deltas(epk)

现在,你可以在模板中执行以下操作:

{% for i in channel_status_list %}
  {{ i|related_deltas:3 }}
{% endfor %}
2020-03-27