Shift N' Tab Shift N' Tab - 2 months ago 5
Python Question

How to display parent model with its child model in a template

Here is my structure:

model.py

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'


I would like to display this on my template just like on this post:
In django How to display parent model data with child model data in change list view?

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.


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

Answer

You have to render your structure with

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

then pass this dict to template:

from django.template import Context, loader

template = loader.get_template('<path_to_your_template>')
context = Context({"doctors": doctors})
template.render(context)

or you can use render shortcut for this part:

render(request, '<path_to_your_template>', {"doctors": doctors})

and render it using double for loop:

{% for title, doc_list in doctors.items %}
    <strong>{{ title }}:</strong><br>
    <ul>
    {% for doc in doc_list %}
      <li>{{ doc }}</li>
    {% endfor %}
    </ul>
{% endfor %}
Comments