d00medman
d00medman

Reputation: 189

How to list all foreign keys associated with an item in Django

I am trying to build a simple listing application with Django. I am using a Language datatype and a Technology datatype which has a language foreign key. I want to display all technologies associated w/a language beneath that language. Here is my current setup:

models.py

from __future__ import unicode_literals
from django.db import models
class Language(models.Model):
    name = models.CharField(max_length = 32)
    def __str__(self):
        return self.name

class Technology(models.Model):
    class Meta:
        verbose_name_plural = 'technologies'
    name = models.CharField(max_length = 32)
    description = models.TextField()
    language = models.ForeignKey(Language)
    def __str__(self):
        return self.name

views.py:

def skills(request):
    return render(request, 'personal/skills.html')

urls.py:

from django.conf.urls import url, include
from . import views
from django.views.generic import ListView
from personal.models import Language, Technology
urlpatterns = [
    url(r'^$', views.index, name='index'), # Defining url patterns. As things stand, we have a start and an end
    url(r'^contact/', views.contact, name='contact'),
    url(r'^skills/$', ListView.as_view(queryset=Technology.objects.all(), template_name='personal/skills.html'))
]

skills.html:

{%extends 'personal/header.html'%}
{%block content%}
  {%for technology in object_list%}
    <h3>{{technology.name}}</h3>
    <h5>{{technology.language}}</h5>
  {%endfor%}
{%endblock%}

I think I need to pass the skills into the template as a second queryset in the URLS file, but I am not really sure. How should I go about the handling of these related datasets to have them return and display in the way I want?

Upvotes: 0

Views: 2839

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

You could return the languages in the QuerySet and then access the technologies from there:

q = Language.objects.all().prefetch_related('technology_set')

...
url(r'^skills/$', ListView.as_view(queryset=q, template_name='personal/skills.html'))

And in your template:

{% block content %}
  {%for lang in object_list %}
    <h3>{{ lang.name }}</h3>
    {% for tech in lang.technology_set.all %} 
        <h5>{{ tech.name }}</h5>
    {% endfor %}
  {% endfor %}
{% endblock %}

Upvotes: 3

Related Questions