Making queries ManyToMany relationships
<p>I have a model named <code>AffectedSegment</code> which is used for store a corporal segments selection.</p>

<pre><code>class AffectedSegment(models.Model):

    SEGMENTO_ESCAPULA = 'EscÃ¡pula'
    SEGMENTO_HOMBRO = 'Hombro'
    SEGMENTO_CODO = 'Codo'
    SEGMENTO_ANTEBRAZO = 'Antebrazo'
    SEGMENTO_CARPO_MUNECA = 'Carpo/MuÃ±eca'
    SEGMENTO_MANO = 'Mano'
    SEGMENT_CHOICES = (
        (SEGMENTO_ESCAPULA, u'EscÃ¡pula'),
        (SEGMENTO_HOMBRO, u'Hombro'),
        (SEGMENTO_CODO, u'Codo'),
        (SEGMENTO_ANTEBRAZO, u'Antebrazo'),
        (SEGMENTO_CARPO_MUNECA, u'Carpo/MuÃ±eca'),
        (SEGMENTO_MANO, u'Mano'),
    )

    affected_segment = models.CharField(
        max_length=12,
        choices=SEGMENT_CHOICES,
        verbose_name='Affected Segment'
    )

    def __str__(self):
        return "%s" % self.affected_segment
</code></pre>

<p>I have another model named  <code>Movement</code>, which is used for store a movement asociated or related with the previous corporal segment entered. </p>

<p>The idea is that one segment (<code>AffectedSegment</code> object) can have many movements, and one movement (<code>Movement</code> object) can be associated with one or many segments.</p>

<pre><code>class Movement(models.Model):
    type = models.CharField(
        max_length=255,
        verbose_name='Movement type'
    )

    corporal_segment_associated = models.ManyToManyField(
        AffectedSegment,
        blank=True,
        verbose_name='Affected segment associated')

    def __str__(self):
        return "%s" % self.type
</code></pre>

<p>This two models, I am referencing in this model</p>

<pre><code>class RehabilitationSession(models.Model):

    affected_segment = models.ManyToManyField(
    AffectedSegment,
    verbose_name='Segmento afectado',
    #related_name='affectedsegment'
    )

    movement = models.ManyToManyField(
    Movement,  # Chained Model
    verbose_name='Movement',
    #related_name = 'movement'
)     
</code></pre>

<p>My main doubt is How to can I lookup the content of <code>affected_segment</code> and    <code>movement</code> fields from <code>RehabilitationSession</code> model in my html templates.</p>

<p>I am trying pass these data of this way:</p>

<p>My views.py file</p>

<pre><code>class RehabilitationSessionList(ListView):

    queryset = RehabilitationSession.objects.all()
    context_object_name = 'rehabilitationsessions'
    template_name = 'finals_list.html'
</code></pre>

<p>And my finals_list.html template is:</p>

<pre><code>&lt;thead&gt;
     &lt;tr&gt;
         &lt;th&gt;Affected Segment&lt;/th&gt;
     &lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{% for a in rehabilitationsessions %}
&lt;tr&gt;   
    &lt;td&gt;{{ a.affected_segment }}&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
{% endfor %}
</code></pre>

<p>But when I access to my template via url, I get this:</p>

<p><a href="http://i.stack.imgur.com/4HHYH.png" rel="nofollow"><img src="http://i.stack.imgur.com/4HHYH.png" alt="enter image description here"></a></p>

<p>Of course, the <code>RehabilitationSession</code> model does not have the <code>affected_segment</code> and <code>movement</code> fields explicitly declared, due to that the ManyToMany relationships create another intermediate models/tables of this way:</p>

<p><a href="http://i.stack.imgur.com/qFuVz.png" rel="nofollow"><img src="http://i.stack.imgur.com/qFuVz.png" alt="enter image description here"></a></p>

<p>Via Django Shell, I can make the queries, navigating through of some of this tables/models</p>

<pre><code>In [21]: RehabilitationSession.objects.filter(movement__type='ExtensiÃ³n')
Out[21]: &lt;QuerySet [&lt;RehabilitationSession: Andrea Vermaelen&gt;]&gt;

In [24]: RehabilitationSession.objects.filter(affected_segment__affected_segment='Codo
...: ')
Out[24]: &lt;QuerySet [&lt;RehabilitationSession: Andrea Vermaelen&gt;]&gt;
</code></pre>

<p>My question is how to can I make the queries in my views for the data appear in the templates, </p>

<p>Is possible that my models are not defined correctly? ...</p>

<p>I know that this should not be complex, but I would like receive some orientation about it for I retrieve the segments and movements of a person in a rehabilitation session.</p>

<p>Any orientation is welcome</p>

<p><strong>UPDATE</strong></p>

<p>In relation to the support that @Daniel-Roseman gave me, I extract also the movement field for attach it in the table.</p>

<pre><code>{% for a in rehabilitationsessions %}
                {% for r in a.affected_segment.all %}
                    {% for l in a.movement.all %}
                         &lt;tr&gt;
                            &lt;td&gt;{{ a.id }}&lt;/td&gt;
                            &lt;td&gt;{{ a.patient.full_name }}&lt;/td&gt;
                            &lt;td&gt;{{ a.patient.user.birth_date }}&lt;/td&gt;
                            &lt;td&gt;{{ a.patient.user.age }}&lt;/td&gt;
                            &lt;td&gt;{{ a.patient.user.sex }}&lt;/td&gt;
                            &lt;td&gt;{{ a.upper_extremity }} &lt;br/&gt;&lt;br/&gt; 
                                &lt;strong&gt;{{ a.pain_extremity }}&lt;/strong&gt; &lt;/td&gt; 
                            &lt;td&gt;{{ a.patient.dominant_superior_member }}&lt;/td&gt;
                            &lt;td&gt;{{ r.get_affected_segment_display }}&lt;/td&gt;

                            &lt;td&gt;{{ l }}&lt;/td&gt;
                            &lt;td&gt; &lt;button type="button" class="btn btn-xs btn-info"&gt;&lt;a href="{% url 'rehabilitationsessions:detail' a.id %}"&gt;Ver&lt;/a&gt;&lt;/button&gt;&lt;/td&gt; 
                            &lt;td&gt;&lt;a href="{% url 'rehabilitationsessions:edit' a.id %}"&gt;Editar&lt;/a&gt;&lt;/td&gt;

                          &lt;/tr&gt;
                    {% endfor %}
                {% endfor %}
            {% endfor %}
</code></pre>

<p>And the movement it's showed. Works.
But when I edit the register for add some additional <code>movement</code> or additional <code>affected_segment</code>, the behavior is that is showed one new record of the this additional segment or movement, although it's not a new record in the database, is a new line of the same record ...</p>

<p>I think that this happened due to my three for loops ... 
It's something like this <a href="https://cldup.com/JRKuSRFPuD.png" rel="nofollow">https://cldup.com/JRKuSRFPuD.png</a>   </p>

<p>As you've said, <code>affected_segment</code> is a many-to-many field. That means it refers to <em>many</em> segments (and the name seems wrong, it should be plural). So you can't just output it, you need to iterate through it:</p>

<pre><code>{% for a in rehabilitationsessions %}
   {% for r in a.affected_segment.all %}
       {{ r.get_affected_segment_display }}
   {% endfor %}
{% endfor %}
</code></pre>

<p>See that since the field you're interested in on AffectedSegment, itself called <code>affected_segment</code>, has choices assigned, you can use <code>get_affected_segment_display</code> to display the readable value of the choice.</p>

python django orm models