鉴于以下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树中每个节点的数据?
答案 0 :(得分: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