Many to many calls in template

4

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

Follow the code below:

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 %}
    
asked by anonymous 19.03.2014 / 02:57

1 answer

2

In many-to-many relationships as well as in many-to-one relationships, you can use them in for through the .all suffix (just as you would in the Python code proj.professor_participante.all() , but 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 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 one-to-many relationship you would have to use the name of the inverse relationship (typically entidade_set - unless you have given it a proper name).

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

    
19.03.2014 / 04:35