【问题标题】:Django 3 combine DetailView and items (ListView) from ManyToMany relationship in one templateDjango 3 将多对多关系中的 DetailView 和项目(ListView)组合在一个模板中
【发布时间】:2020-05-14 06:02:58
【问题描述】:

我正在开发一个 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”联结表包含我正在测试的特定人员的产品条目。

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

【问题讨论】:

    标签: django django-templates django-queryset


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

    • 您的第一个建议立即奏效。谢谢!现在尝试扩展到与产品相关的其他模型。感谢您的帮助。
    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 2012-03-05
    • 2020-03-06
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多