Search code examples
djangodjango-mpttmptt

MPTT - How can I pass extra data for each node to the template?


Given the following view:

def comments(request):

    comments_list = Thing.objects.filter(thing_type=2)
    #Thing model extends MPTTModel 
    comments_extra_data_list = Data.objects.filter(thing__in=comments_list)
    #Data objects have data for each Thing

    return render_to_response("comments.html",
                      {'nodes':comments_list},
                        context_instance=RequestContext(request))

How can I pass comments_extra_data_list to the template in order to display the data for each node at MPTT tree?


Solution

  • If you have these models:

    class Thing(MPTTModel):
        ...
        thing_type = models.IntegerField(default=0)
    
    class Data(models.Model):
        thing = models.ForeignKey(Thing, related_name="data_set")
    

    You can just do this in your template:

    {% recursetree nodes %}
        <h1>{{ node }}</h1>
        {% for data in node.data_set.all %}
            {{ data.something }}
        {% endfor %}
        ...
    {% endrecursetree %}
    

    That's the naive approach. It will do one database query (fetching related Data objects) for each Thing.

    If you're using django 1.4, you should prefetch the data objects in your view, so it doesn't do so many queries:

    comments = Thing.objects.filter(thing_type=2)
    comments = comments.prefetch_related('data_set')
    

    https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related