首页 > 解决方案 > django generic view: detail in category

问题描述

I use a generic view to list my categories. I would also like to display the title of each items belonging to these categories. I understand the principle of ListView and DetailView but what about some details in lists ?

Here are my different files:

Models.py

class categories(models.Model):
    name = models.CharField(max_length=50,unique=True)
    slug = models.SlugField(max_length=100,unique=True)

    def __str__(self):
        return self.name

class details(models.Model):
   title = models.CharField(max_length=100)
   author = models.CharField(max_length=42)
   category = models.ForeignKey('categories', on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Views.py

class IndexView(generic.ListView):
    model = categories
    context_object_name = "list_categories"
    template_name='show/index.html'

Urls.py

urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]

Index.html

{% load static %}

<p>These is a list of categories</p>

{% for category in list_categories %}
    <div class="article">
       <h3>{{ category.name }}</h3>

        {% for title in category.detail %}
            <p> {{title}} </p>
        {% endfor %}
    </div>
{% endfor %}

标签: pythondjango

解决方案


您需要先反向调用details相关名称,即“类别”。

{% load staticfiles %}

<p>These is a list of categories</p>

{% for category in list_categories %}
    <div class="article">
       <h3>{{ category.name }}</h3>

        {% for detail in category.categories.all %}
            <p> {{detail.title}} </p>
        {% endfor %}
    </div>

请注意,您必须all在 reverse all 之后使用,因为可能存在多个反向关系。

有什么疑惑可以在下方评论。


推荐阅读