django - Django 3 将多对多关系中的 DetailView 和项目(ListView)组合在一个模板中
问题描述
我正在做一个 Django 3 项目,我试图将人们与他们使用的产品联系起来。最终目标是显示人员的详细视图(DetailView)并包括他们使用的产品列表(ListView?)。这是我的模型、视图和模板中的内容:
# models.py (omitting non-relevant fields)
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=75, db_index=True)
products = models.ManyToManyField('Product', through='PersonProduct')
class Product(models.Model):
name = models.CharField("Product Name", max_length=75)
class PersonProduct(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
created = models.DateTimeField(default=timezone.now)
# views.py
class PersonDetailView(DetailView):
model = Person
queryset = Person.objects.all()
template_name = 'person_detail.html'
# person_detail.html (simplified for clarity)
{% extends 'base.html' %}
{% block content %}
<div class="person-detail">
<h2>{{ person.first_name }} {{ person.last_name }}</h2>
</div>
<div class="gear-list">
<ul>
<!--
This is where I'm stuck. I know I need to iterate over the products
that are associated with the person, but I can't figure out how to do it.
-->
</ul>
</div>
{% endblock content %}
该页面可以很好地呈现该人的详细信息,但他/她使用的产品根本没有任何内容。我已经确认“PersonProduct”联结表包含我正在测试的特定人员的产品条目。
我知道我对它应该如何工作的理解存在很大差距,但我无法在任何地方找到答案。欢迎提出解决此问题的建议以及其他阅读/学习资源的建议。
解决方案
你可以这样做:
{% for product in person.products.all %}
<li>{{ product.name }}</li>
{% endfor %}
或者,如果您需要through
表格中的日期:
{% for personproduct in person.personproduct_set.all %}
<li>{{ personproduct.products.name }} - {{ personproduct.created }}</li>
{% endfor %}
推荐阅读
- javascript - 使用 Switch Javascript 选择选项 HTML
- r - 将 Twitter 数据转换成整洁的格式
- python - 如何对字典中仅一个键值列表中的项目进行排序
- html - 当单元格跨越 n 列时,如何将表格列向下移动?
- groovy - 断言结果如何仅获取计数
- javascript - 页面刷新时带有正文和重定向页面的 Jquery 发布请求
- base64 - XSLT - 将 XML 元素编码为 base64 编码字符串
- reactjs - 我可以将 React Bootstrap 与 Next.js 一起使用吗?
- python - conda 无法识别已安装的软件包
- azure - 使用 Dapper 进行 aync 可能会导致 SQL Azure“弹性池的请求限制为 100 且已达到”