0

鉴于以下情况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))

如何传递comments_extra_data_list给模板以便在 MPTT 树上显示每个节点的数据?

4

1 回答 1

3

如果您有以下型号:

class Thing(MPTTModel):
    ...
    thing_type = models.IntegerField(default=0)

class Data(models.Model):
    thing = models.ForeignKey(Thing, related_name="data_set")

您可以在模板中执行此操作:

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

这是天真的方法。它将Data为每个Thing.

如果你使用 django 1.4,你应该在你的视图中预取数据对象,所以它不会做这么多的查询:

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

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

于 2012-03-28T08:13:23.873 回答