Calls Many to Many in template

Asked

Viewed 207 times

4

I would like to know how to make a template call to a field Many to Many of the models.

Follows code:

Models

class Projeto(models.Model):
professor_participante = models.ManyToManyField(Servidor,   verbose_name=u'Professores participante', blank=True)

Views

def projeto(request):
context={}
context['projeto'] = Projeto.objects.all()
return render(request, 'projeto.html', context)

template

{% for projetos in projeto %}
<li>Professor participante - {{ projetos.professor_participante }}</li>
{% endfor %}

1 answer

2

Both in many-to-many relationships and in many-to-one relationships, one can use them in one for through the suffix .all (the same way you would in Python code proj.professor_participante.all(), only without the parentheses at the end).

{% for projetos in projeto %}
    <ul>
    {% for professor in projetos.professor_participante.all %}
        <li>Professor participante - {{ professor.nome }}</li>
    {% endfor %}
    </ul>
{% endfor %}

Here it is the documentation for calling methods within a template. The only difference is that in this case (Many-to-Many) just use the name of the field, while in a relation of one to many you would have to use the name of the inverse relation (typically entidade_set - unless you have given it a proper name).

P.S. Why are you calling your list from projeto (in the singular) and each individual element of projetos (plural)? I gave the answer according to the question, but the ideal would be to change these names.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.