0

I'm without clues on solving this problem.

I've a template tag that receives an Object:

{% score_for_object OBJECT_HERE as score2 %}

The problem is that I'm passing to the template a context that came from a raw select:

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

To solve the problem of the template tag that accepts a Django object, I've write a template tag:

'''
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)

With this template tag I expected this to work:

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

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

My question. It is possible to retrieve an object from a template tag?

Best Regards,

André
  • 24,706
  • 43
  • 121
  • 178

1 Answers1

2

To get the score:

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 %}
catherine
  • 22,492
  • 12
  • 61
  • 85