小编Oll*_*aho的帖子

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

我有这样的情况:有三个 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 …
Run Code Online (Sandbox Code Playgroud)

django django-templates django-views

4
推荐指数
1
解决办法
2485
查看次数

标签 统计

django ×1

django-templates ×1

django-views ×1