首页 > 解决方案 > 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”联结表包含我正在测试的特定人员的产品条目。

我知道我对它应该如何工作的理解存在很大差距,但我无法在任何地方找到答案。欢迎提出解决此问题的建议以及其他阅读/学习资源的建议。

标签: djangodjango-templatesdjango-queryset

解决方案


你可以这样做:

{% 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 %}

推荐阅读