2013-03-16 115 views
0

我没有解决这个问题的线索。Django - 如何从自定义模板标签中检索对象?

我已经接收的对象的模板标签:

{% 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 %} 

我的问题。有可能从模板标签中检索一个对象?

最好的问候,

+0

你想唯一的比分在该标签被通过? – catherine 2013-03-16 14:01:25

回答

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 %}