Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: Traversing multiple successive ManyToMany relationships in templates in one loop
    primarykey
    data
    text
    <p>I have a situation like this: there are three Django models, let's call them article, section and tag, and one through-model.</p> <pre><code>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() </code></pre> <p>Then, in the section's detail template, I want to list all the tags from the related articles. To do that, I first have to traverse the Section-Article ManyToMany relationship in reverse (using the related_name), and then traverse the Article-Tag ManyToMany relationship. I tried this:</p> <pre><code>{# doesn't print anything: #} {% for tag in object.articles.tags.all %} {{ tag.name }} {% endfor %} </code></pre> <p>but for some reason, that didn't work. {% for tag in object.articles.all.tags.all %} didn't work either. I can print all the tags using nested loops, but that means duplicates become a problem.</p> <pre><code>{# duplicates are an issue here: #} {% for article in object.articles.all %} {% for tag in article.tags.all %} {{ tag.name }} {% endfor %} {% endfor %} </code></pre> <p>Is there a neat way to do this in Django templates, or do I have to put it in the view code? If so, what would be the be the cleanest way to do it there so I can avoid duplicate tags in the list?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload