Django:在一个循环中遍历模板中的多个连续多对多关系

Oll*_*aho 4 django django-templates django-views

我有这样的情况:有三个 Django 模型,我们称它们为 article、section 和 tag,还有一个 through-model。

class Tag(models.Model):
    name = models.CharField(max_length=100, primary_key=True)

class Section(models.Model):
    # all sorts of fields here

class Article(models.Model):
    tags = models.ManyToManyField(Tag, null=True, blank=True)
    sections = models.ManyToManyField(Section, null=True, blank=True, through='SectionInArticle', related_name='articles')

class SectionInArticle(models.Model):
    article = models.ForeignKey(Article)
    section = models.ForeignKey(Section)
    order = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

然后,在该部分的详细信息模板中,我想列出相关文章中的所有标签。为此,我首先必须反向遍历 Section-Article ManyToMany 关系(使用 related_name),然后遍历 Article-Tag ManyToMany 关系。我试过这个:

{# doesn't print anything: #}
{% for tag in object.articles.tags.all %}
{{ tag.name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,这不起作用。{% for tag in object.articles.all.tags.all %} 也不起作用。我可以使用嵌套循环打印所有标签,但这意味着重复会成为一个问题。

{# duplicates are an issue here: #}
{% for article in object.articles.all %}
  {% for tag in article.tags.all %}
    {{ tag.name }}
  {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

在 Django 模板中是否有一种巧妙的方法可以做到这一点,还是必须将它放在视图代码中?如果是这样,那么在那里做这件事的最干净的方法是什么,这样我就可以避免列表中的重复标签?

小智 5

您正在寻找的过滤器基本上是:

Tag.objects.filter(article__sections=section)
Run Code Online (Sandbox Code Playgroud)

您可以将其放在您的视图中,也可以将其作为属性添加到您的 Section 模型中:

class Section(models.Model):
# all sorts of fields here
@property
def tags(self):
    return Tag.objects.filter(article__sections=self).all()
Run Code Online (Sandbox Code Playgroud)

然后在模板中执行:

{% for tag in object.tags %}
    {{ tag.name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)