[Fixed]-How to display parent model with its child model in a template

1👍

✅

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 %}

Leave a comment