我有一个模型房间的详细视图,在get_context_data方法中我向我的上下文添加了另一个来自第二个模型的对象查询集:Worker
class RoomView(DetailView):
template_name = 'detail.html'
model = Room
context_object_name = "room"
def get_object(self):
object = super(RoomView, self).get_object()
if not self.request.user.is_authenticated():
raise Http404
return object
def get_context_data(self, **kwargs):
context = super(RoomView, self).get_context_data(**kwargs)
context['workers'] = Worker.objects.all()
print context
return context
上下文如下:
{'workers': [<Worker: Michael Shchur, Backend>, <Worker: Toto Kutunyo, Backend>], u'object': <Room: Backend, id=1>, 'room': <Room: Backend, id=1>, u'view': <map.views.RoomView object at 0x7f257811dc10>}
但我无法使用{{room.workers}}或
访问此添加的对象列表{% for worker in room.workers %}
<tr>
<td>{{worker.id}}</td>
<td>{{worker.first_name}}</td>
<td>{{worker.last_name}}</td>
<td>{{worker.email}}</td>
</tr>
{% endfor %}.
请告诉我,我能做到吗。
答案 0 :(得分:0)
您将此查询集放在名为'workers'的上下文中,因此请从此名称中检索它:
{% for worker in workers %}
<tr>
<td>{{worker.id}}</td>
<td>{{worker.first_name}}</td>
<td>{{worker.last_name}}</td>
<td>{{worker.email}}</td>
</tr>
{% endfor %}.