如何在模板中显示父模型及其子模型

时间:2016-09-11 14:41:02

标签: python django django-models

这是我的结构:

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'

我想在我的模板上显示这个,就像在这篇帖子上一样: 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.

但问题是我有很多关系结构。我是django的新手,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你必须使用

渲染你的结构
app.controller("angularJsController", function ($scope, $location, $http, user1Constant, user2Constant, databaseService) {
    databaseService[user1Constant + 'Request'].done(function() {
        /* Now I can get databaseService[user1Constant] */
    });
});

然后将此dict传递给模板:

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

或者您可以使用render此部分的快捷方式:

from django.template import Context, loader

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

并使用双render(request, '<path_to_your_template>', {"doctors": doctors}) 循环渲染它:

for