将参数传递给Django模板中的模型方法 [英] Passing arguments to model methods in Django templates
问题描述
我正在尝试从指定的业务中获取所有客户,但是Customer模型中有一个类方法可基于同一业务获取一些信息...让我用代码来解释一下...
I'm trying to get all customers from a specified business, but there is a class method in Customer model to get some information based on the same Business... Let me explain this with code...
class Business(models.Model):
...
customers = models.ManyToManyField(Customer, blank=True, null=True)
class Customer(models.Model):
...
def get_something(self, obj_business)
...
好的,现在在我看来,我从这样的指定企业获得了所有客户:
Ok now in my views I get all customers from a specified business like this:
obj_customers = obj_business.customers.all()
然后我尝试将其打印在模板中:
Then I try to print this in my template:
{% for obj_customer in obj_customers %}
{{ obj_customer.get_something ....... }}
但是是的,没有办法传递参数...我想知道是否缺少某些东西...
But yes, there is not a way to pass arguments... I would like to know if there is something that I'm missing...
I想知道是否还有另一种解决方案而不是创建模板标签...因为它是ManyToManyField,如果 customers 字段只是ForeignKey,则不需要将参数传递给该方法...
I wonder if there is another solution instead creating a template tag... because it is a ManyToManyField, if customers field had been just ForeignKey, no need to pass an argument to that method...
推荐答案
您可以创建一个简单的模板标签来调用带有任何参数的任何方法:
You can create a simple template tag to call any method with any arguments:
from django import template
register = template.Library()
@register.simple_tag
def call_method(obj, method_name, *args):
method = getattr(obj, method_name)
return method(*args)
然后在您的模板中:
{% call_method obj_customer 'get_something' obj_business %}
但是,当然,创建专用模板标签的安全性更高:-)
But, of course, crating of a specialized template tag is more safe :-)
@register.simple_tag
def get_something(customer, business):
return customer.get_something(business)
模板:
{% get_something obj_customer obj_business %}
这篇关于将参数传递给Django模板中的模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!