python - 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 %}
解决方案
您需要先反向调用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 之后使用,因为可能存在多个反向关系。
有什么疑惑可以在下方评论。
推荐阅读
- charts - 如何为 splunk timechart 命令添加总计和百分比列
- ssas - Adventureworks 以外的 OLAP 数据集?
- python - 颤振 PUT 请求
- angular - Angular:从 .subscribe() 内部返回的字符串会导致无限的 xhr 请求
- java - Selenium 文件上传错误-> org.openqa.selenium.ElementNotInteractableException:元素不可交互
- css - 定位整个文档中的奇数元素,而不仅仅是兄弟姐妹
- php - 我希望我的日期格式为 09:54:24
- javascript - 错误:在我的 NodeJS 应用程序中找不到模块“../../models/blog”
- c++ - 计算彼此之间数字的平均值 C++
- python - 使用 telnetlib 在 telnet 期间从 tn.write() 获取输出