django 模板系统,在模型内部调用函数 [英] django template system, calling a function inside a model
问题描述
我想在模板中从我的模型中调用一个函数,例如:
I want to call a function from my model at a template such as:
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 传递为
And when I want to call this from the template: assume while rendering, I pass channel_status_list as
channel_status_list = ChannelStatus.objects.all()
{% for i in channel_status_list %}
{{ i.get_related_deltas(3) }}
{% endfor %}
这不起作用,我可以调用一个不消耗任何东西的函数,但如果它有参数,则无法找到该怎么做
This doesn't work, I am able to call a function that consumes nothing, but couln't find what to do if it has parameter(s)
干杯
推荐答案
不能从模板调用带有参数的函数.您只能在视图中执行此操作.或者,您可以编写一个 自定义模板过滤器,可能看起来像这样:
You can't call a function with parameters from the template. You can only do this in the view. Alternatively you could write a custom template filter, which might look like this:
@register.filter
def related_deltas(obj, epk):
return obj.get_related_deltas(epk)
所以现在您可以在模板中执行此操作:
So now you can do this in the template:
{% for i in channel_status_list %}
{{ i|related_deltas:3 }}
{% endfor %}
这篇关于django 模板系统,在模型内部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!