Got 4 Models:
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')
What I'm trying to do is:
Create DetailView of a Buildings in which we see:
Now in views.py I have:
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 In DetailView I can now access Rooms, Departments and Zones but I'cant match Zones to Rooms. It prints buildings and rooms with departments correctly, then multiplies it with all Zones in building.
{% for rm in Rooms %}
{% for zn in Zones %}
<p> {{ rm.name }} </p>
<p> {{ rm.department }} </p>
<p> {{ zn.name }} </p>
{% endfor %}
{% endfor %}
Output:
Room 1
Depart A
Zone 1
Room 1
Depart A
Zone 2
etc.
How can I match Zone name to corresponding Department of each Room in a Building correctly? Room and Depart name is matched correctly.
You are looping over separate querysets which won't match up, just access the related models from the instance you have. Try this in the template:
{% for rm in Rooms %}
<p> {{ rm.name }} </p>
<p> {{ rm.department }} </p>
<p> {{ rm.department.zone.name }} </p>
{% endfor %}