如何在模板中对ManyToMany进行分组

时间:2011-11-22 14:53:04

标签: django django-templates

这是我的模特:

class Teacher(models.Model):
    name = models.CharField(max_length=50)  
    subjects = models.ManyToManyField(Subject)

class Subject(models.Model):
    name = models.CharField(max_length=50)
    type = models.ForeignKey(SubjectType)   

class SubjectType(models.Model):
    name = models.CharField(max_length=50)

我想在模板中做类似的事情:

{regroup subjects by subject.type}
  {foreach subject_type}
    #display all teachers for subject_type         

每个主题都有teacher_set。 我怎样才能将所有教师与特定的subject_type联合起来?

1 个答案:

答案 0 :(得分:3)

我认为您无法从模板中获取此功能。但是,您可以在视图中执行此操作:

subject_type = # Some SubjectType object
my_teachers = []
for subject in subject_type.subject_set:
    my_teachers += subject.teacher_set
# What we do with the duplicates?
my_teachers = list(set(my_teachers))

现在,您有my_teachers中针对特定主题类型的唯一教师列表。

编辑:您可以为每个SubjectType对象执行此操作,并将结果列表(列表)传递给模板。