0

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?

bentzy
  • 301
  • 2
  • 4
  • 15

1 Answers1

3

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

craigds
  • 2,072
  • 14
  • 25
  • how'd you get on? If that's what you were looking for, don't forget to accept the answer. Then we both get improved SO reputation :) – craigds Mar 28 '12 at 13:28