在模板中显示Django多对多

时间:2014-02-15 11:07:57

标签: django

我想在模板中列出游戏中的玩家

<h1>{{ game.name }}</h1>

<p> Players: </p>{{game.Players.all|join:", "}}

上面的代码给了我用逗号分隔的名字,但我想做一些像

这样的事情
{% for Player in Players %}
    {{Player}}
{% endfor %}

我的models.py是

class PlayerProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    bday = models.DateField(default=0)
    block = models.CharField(max_length=40)
    Sports = models.ManyToManyField(Sport)
    def __str__(self):
        return self.user.username

class Game(models.Model):
    Players = models.ManyToManyField(PlayerProfile)
    name = models.CharField(max_length=40)
    def __unicode__(self):
        return self.name

任何人都可以帮助我吗?感谢。

1 个答案:

答案 0 :(得分:0)

{% for player in game.Players.all %}
    {{ player.bday }} # or another field you want
{% endfor %}

应该帮助