How to display parent model with its child model in a template
<p>Here is my structure:</p>

<p><strong>model.py</strong></p>

<pre><code>class Doctor(models.Model):
    name = models.CharField(max_length=50)
    room_no = models.IntegerField()
    floor_no = models.IntegerField()
    contact_no = models.CharField(max_length=50, blank=True, null=True)
    notes = models.CharField(max_length=70, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'doctor'

class DoctorSpecialization(models.Model):
    doc = models.ForeignKey(Doctor, models.DO_NOTHING)
    spec = models.ForeignKey('Specialization', models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'doctor_specialization'

class Specialization(models.Model):
    title = models.CharField(unique=True, max_length=45)

    class Meta:
        managed = False
        db_table = 'specialization'
</code></pre>

<p>I would like to display this on my template just like on this post:
<a href="http://stackoverflow.com/questions/30435949/in-django-how-to-display-parent-model-data-with-child-model-data-in-change-list">In django How to display parent model data with child model data in change list view?</a></p>

<pre><code>Internal Medicine
 - Joanne Doe M.D.
 - Andrew Fuller M.D.
 - Nancy Davolio M.D.
OB-Gyne
 - John Doe M.D.
 - Janet Leverling M.D.
ENT
 - Margaret Peacock M.D.
 - Steven Buchanan M.D.
 - Laura Callahan M.D.
 - Michael Suyama M.D.
</code></pre>

<p><strong>But the problem is i have many to many relationship structure. I am new to django please your help is highly appreciated.</strong></p>

<p>You have to render your structure with</p>

<pre><code>doctors = {}
for spec in Specialization.objects.all():
    doctors[spec.title] = [doc_spec.doc.name for doc_spec in DoctorSpecialization.objects.filter(spec=spec)]
</code></pre>

<p>then pass this dict to template:</p>

<pre><code>from django.template import Context, loader

template = loader.get_template('&lt;path_to_your_template&gt;')
context = Context({"doctors": doctors})
template.render(context)
</code></pre>

<p>or you can use <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render" rel="nofollow"><code>render</code></a> shortcut for this part:</p>

<pre><code>render(request, '&lt;path_to_your_template&gt;', {"doctors": doctors})
</code></pre>

<p>and render it using double <code>for</code> loop:</p>

<pre><code>{% for title, doc_list in doctors.items %}
    &lt;strong&gt;{{ title }}:&lt;/strong&gt;&lt;br&gt;
    &lt;ul&gt;
    {% for doc in doc_list %}
      &lt;li&gt;{{ doc }}&lt;/li&gt;
    {% endfor %}
    &lt;/ul&gt;
{% endfor %}
</code></pre>

python django django-models