Category Archives: Django

Clicking through links in a generic DetailView

Creating views in Django without much background in it can be a daunting task. Since I am working on an application to view and track fiber optic cables on campus, I wanted to be able to see what LAN rooms are in a building that I’m viewing using a generic DetailView.

To accomplish this, I found out that you can call on model relationships in order to see which models have a foreign key for the selected building.

Here is where I called the DetailView generic view in

from django.views.generic import DetailView

# Buildings

Here is what I placed in my template for buildings_detail.html to do this:

    {% for lanroom in building.lanroom_set.all %}
    <li><a href="/lanrooms/{{ }}/">{{ lanroom.lan_room_name }}</a></li>
    {% endfor %}

Calling lanroom_set.all on the building passed through to the template lets me list all of the LAN rooms in that building right on its DetailView page!

Final output looks like this:

Donnelly Hall

It took some hunting online to find the best way to do this, and this is what worked for me in the end! It’s worth noting that this will probably not be the most efficient way to access the database in this scenario, as it seems to require n+1 queries for the number of LAN rooms, but right now I am building things out before they are optimized.