Django - 如何从自定义模板标签中检索对象?

时间:2013-03-16 13:44:39

标签: django django-templates django-voting

我没有解决这个问题的线索。

我有一个接收对象的模板标记:

{% score_for_object OBJECT_HERE as score2 %}

问题是我正在向模板传递来自原始选择的上下文:

cursor = connection.cursor()
cursor.execute("select ...") 
comments = utils.dictfetchall(cursor)

为了解决接受Django对象的模板标签的问题,我写了一个模板标签:

'''
This template tag is used to transform a comment_id in an object to use in the django-voting app
'''
def retrive_comment_object(comment_id):
    from myapp.apps.comments.models import MPTTComment
    return MPTTComment.objects.get(id=comment_id)

使用此模板标记我希望这可以工作:

{% for item in comments %}
    {% score_for_object item.comment_id|retrieve_comment_object as score2 %}

    {{ score2.score }} {# expected to work, but not working #}
{% endfor %}

我的问题。可以从模板标签中检索对象吗?

最诚挚的问候,

1 个答案:

答案 0 :(得分:2)

获得分数:

from django import template
from myapp.apps.comments.models import MPTTComment

register = template.Library()

@register.simple_tag
def retrive_comment_object(comment_id):
    data = MPTTComment.objects.get(id=comment_id)
    return data.score


{% for item in comments %}
    Score: {% retrive_comment_object item.comment_id %}
{% endfor %}