ng150716
ng150716

Reputation: 2244

Show Objects and Relevant Sub-Objects

I have two models, Category and Topics. Each Topic belongs to a Category (via foreign key). What i want to do in my template is display a category, and then under it show all the topics that have been filed under that specific category. Here is my models.py:

class Category(models.Model):
    name = models.CharField(max_length=55)

class Topic(models.Model):
    category = models.ForeignKey(Category)
    name = models.CharField(max_length=55)

Any idea on how I can accomplish this? Thanks.

Upvotes: 0

Views: 104

Answers (1)

tdsymonds
tdsymonds

Reputation: 1709

As mentioned in the comments, you want to follow the relationship backwards.

In your view you'll need to pass your categories to the template, something like:

 from django.views.generic import TemplateView
 from .models import Category 

 class MyView(TemplateView):
     template_name = 'path/to/my/template.html'

     def get_context_data(self, **kwargs):
         context = super().get_context_data(**kwargs)
         context['categories'] = Category.objects.all()
         return context   

Then in your template you can achieve that as follows:

{% for category in categories %}
    <h3>{{ category.name }}</h3>
    <ul>
        {% for topic in category.topic_set.all %}
            <li>{{ topic.name }}</li>    
        {% endfor %}
    </ul>
{% endfor %}

Upvotes: 1

Related Questions