开发者

Django: Traversing multiple successive ManyToMany relationships in templates in one loop

I have a situation like this: there are three Django models, let's call them article, section and tag, and one 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()

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:

{# doesn't print anything: #}
{% for tag in object.articles.tags.all %}
{{ tag.name }}
{% endfor %}

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.

{# duplicates are an issue here: #}
{% for article in object.articles.all %}
  {% for tag in article.tags.all %}
    {{ tag.name }}
  {% endfor %}
{% endfor %}

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?


The filter you are looking for is basically:

Tag.objects.filter(article__sections=section)

You can put it the your view, or you could for add it to your Section model as a property:

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

And then in the template do:

{% for tag in object.tags %}
    {{ tag.name }}
{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜