Django DetailView:相关对象

Django DetailView: related objects

获得 4 个模型:

models.py

class Buildings(models.Model):
    name = models.CharField(max_length=25)

class Zones(models.Model):
    name = models.CharField(max_length=25)

class Departments(models.Model):
    name = models.CharField(max_length=25)
    zone = models.ForeignKey(Zones, related_name='departments')

class Rooms(models.Model):
    name = models.CharField(max_length=25)
    department = models.ForeignKey(Departments, related_name='rooms')
    building = models.ForeignKey(Buildings, related_name='buildings')

我想做的是:

创建我们在其中看到的建筑物的 DetailView:

现在 views.py 我有:

class BuildingsDetailView(DetailView):
    model = Buildings

    def get_context_data(self, **kwargs):
        context = super(BuildingsDetailView, self).get_context_data(**kwargs)
        context['Rooms'] = Rooms.objects.filter(building=self.get_object())
        context['Zones'] = Zones.objects.filter(departments__rooms__buildings=self.get_object())
        return context

detail.html 在 DetailView 中,我现在可以访问房间、部门和区域,但我无法将区域与房间匹配。它正确打印带有部门的建筑物和房间,然后将其与建筑物中的所有区域相乘。

{% for rm in Rooms %}
    {% for zn in Zones %}
        <p> {{ rm.name }} </p>
        <p> {{ rm.department }} </p>
        <p> {{ zn.name }} </p>
    {% endfor %}
{% endfor %}

输出:

Room 1
Depart A
Zone 1

Room 1
Depart A
Zone 2

等等

如何将区域名称正确匹配到建筑物中每个房间的相应部门? 房间和离开名称匹配正确。

您正在遍历不匹配的单独查询集,只需从您拥有的实例访问相关模型。在模板中试试这个:

{% for rm in Rooms %}
    <p> {{ rm.name }} </p>
    <p> {{ rm.department }} </p>
    <p> {{ rm.department.zone.name }} </p>
{% endfor %}