Irmantas Želionis
Irmantas Želionis

Reputation: 2324

How to show ManyToMany model in template?

Here is my 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)

Here is views:

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

I am trying to show champ1 name. However, this doesn't help:

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

What to do?

Upvotes: 0

Views: 36

Answers (1)

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

matchups is a collection

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

Upvotes: 1

Related Questions