如何在模板中访问ManyToManyField的多个图层?

时间:2012-07-15 22:52:18

标签: django django-templates many-to-many

我有三个'层'深度模型,我想通过我的模板访问:

型号:

class Match(models.Model):

    pl1 = models.IntegerField(default=0)
    pl2 = models.IntegerField(default=0)
    boards = models.ManyToManyField(Scoreboard)
    active = models.IntegerField(default=1)
    turn = models.IntegerField(default=0)

    def __unicode__(self):
        return "Match " + str(self.id)

class Scoreboard(models.Model):

    user = models.ForeignKey(User)

我只是在猜测,但为了获得与每个“匹配”相关的用户名,不应该是这样的:

{% for active in matches %}
{{active}} - {{active.boards.user}}<br>
{% endfor %}

1 个答案:

答案 0 :(得分:2)

boards是ManyToMany,因此每个match都有多个记分板。所以,你需要迭代它们。

{% for active in matches %}
  {{ active }}:
  {% for board in active.boards.all %}
      {{ board.user }}
  {% endfor %}
{% endfor %}