如何在模板中显示ManyToMany模型?

时间:2015-11-15 18:19:11

标签: python django django-models

这是我的模特:

class Champion(models.Model):
    name = models.CharField(max_length=140)
    role = models.CharField(max_length=140)

    def __unicode__(self):
        return self.name + " - " + self.role

class Matchup(models.Model):
    champ1 = models.ManyToManyField(Champion, related_name='champ1')
    champ2 = models.ManyToManyField(Champion, related_name='champ2')
    rate = models.DecimalField(max_digits=20, decimal_places=4)
    minute = models.IntegerField()
    gold = models.DecimalField(max_digits=20, decimal_places=4)

以下是观点:

def adc(request):
    matchups = Matchup.objects.filter(champ1__role = "ADC")
    return render(request, 'ADC.html', { 'matchups' : matchups})

我正在尝试显示champ1名称。但是,这没有帮助:

{%for i in matchups.champ1.all%}
{{i.name}} 
{%endfor%}

怎么办?

1 个答案:

答案 0 :(得分:1)

matchups是一个集合

{% for m in matchups.all %}
  {% for i in m.champ1.all %}
    {{ i.name }} 
  {% endfor %}
{% endfor %}