2011-03-14 29 views
2

我有這樣的情況:有三個Django模型,我們稱它們爲article,section和tag,以及一個through-model。Django:在一個循環中遍歷模板中的多個連續ManyToMany關係

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() 

然後,在該部分的詳細模板中,我想列出相關文章中的所有標籤。要做到這一點,我首先必須反過來(使用related_name)遍歷Section-Article ManyToMany關係,然後遍歷Article-Tag ManyToMany關係。我試過這個:

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

但由於某些原因,這並沒有奏效。 {%for object 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 %} 

在Django模板中有沒有一種簡潔的方式來做到這一點,還是我必須把它放在視圖代碼中?如果是這樣,在那裏做最乾淨的方法是什麼,這樣我可以避免列表中的重複標籤?

回答

4

你正在尋找的過濾器基本上是:

Tag.objects.filter(article__sections=section) 

你可以把它放在你的看法,或者你可以爲它添加到您的第模型屬性:

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

而且然後在模板中做:

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

謝謝!這似乎是訣竅,而且非常優雅。 – 2011-03-14 14:39:23

+0

好戲。謝謝! – Gnijuohz 2012-09-23 04:38:43