2012-07-31 39 views
0

我有一个像模型的Django的获取属性动态

class Document(models.Model): 
    comment = models.TextField(null=True,blank=True) 
    upload_date = models.DateTimeField(blank=False) 

文档对象模型在模板列为

{% for doc in doc_list %} 
    {{ doc.comment }} 
    {{ doc.upload_date }} 
{% endfor %} 

不过,我想达到的doc性质类似动态

{{ doc."comment" }} 

{{ doc|getField:"comment" }} 

我该怎么做?

感谢

+1

你是什么意思时,你说“dinamically”吗?如果你能做'{{doc。'comment'}}',你会得到什么结果?您希望将这与“{{doc.comment}}”区别开来吗? – marianobianchi 2012-07-31 19:56:02

回答

2

我假定你的意思是你想使用另一种变量,你不一定知道的时间访问一个模型领域。因此,您可能会将some_var传递到模板中,并且这是模型中您希望显示的字段,例如comment或upload_date。

你可以建立一个template tag做到这一点:

@register.simple_tag 
def get_model_attr(instance, key): 
    return getattr(instance, key) 

现在在你的模板类的东西,你可以这样做:

{% for doc in doc_list %} 
    {% get_model_attr doc "comment" %} 
    {% get_model_attr doc some_var %} 
{% endfor %}