2017-08-03 102 views
0

我有两个模型,类别和主题。每个主题属于一个类别(通过外键)。我想在我的模板中执行的操作是显示一个类别,然后在其下显示在该特定类别下提交的所有主题。这是我的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) 

任何想法,我怎么能做到这一点?谢谢。

+0

参见[以下关系向后(https://docs.djangoproject.com/en/1.11/topics/db/queries/#backwards-related-objects)。 –

回答

1

正如评论中所提到的,您想要关注后面的关系。

在你看来,你需要将自己的类别传递给模板,一样的东西:

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 

然后在你的模板,你可以做到这一点,如下所示:

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