所以我有这两个型号。我的课程模型与ManytoMany字段链接到ax.xaxis.set_tick_params(length=0,labelbottom=False)
。当我尝试在模板中渲染教师时,不会显示任何结果。有什么问题?
TeacherData
class TeacherData(models.Model):
name = models.CharField(max_length=30)
surname = models.CharField(max_length=50)
teacher_ID = models.CharField(unique=True, max_length=14)
notes = models.CharField(max_length=255, default=None, blank=True)
class Meta:
verbose_name = "Teacher Data"
verbose_name_plural = "Teachers Data"
def __str__(self):
return self.surname
class Course(models.Model):
study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='')
name = models.CharField(max_length=50, unique=True)
ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
description = models.TextField()
year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
semester = models.IntegerField(choices=((1, "1"),
(2, "2"),
), default=None)
teacher = models.ManyToManyField('TeacherData', verbose_name="Taught By")
slug = models.SlugField(max_length=140, unique=True)
def __str__(self):
return self.name
<ul>
{% for c in courses.all %}
<li>{{ c.study_programme }}</li>
<li>{{ c.name }}</li>
<li>{{ c.ects }}</li>
<li>{{ c.description }}</li>
<li>{{ c.year }}</li>
<li>{{ c.semester }}</li>
<li>{{ c.teacher }}</li>
{% endfor %}
</ul>
答案 0 :(得分:1)
在您的模板中,c.teacher
将是Django的ManyToMany- 经理(如课程。对象是经理)。我想这只会被渲染成一个空字符串。请尝试使用c.teacher.all
。这将为您提供与课程相关的所有教师的 QuerySet 。
如果您需要更精细的模板,这里是主要结构:
<ul>
{% for c in courses.all %}
<li>{{ c.study_programme }}</li>
<li>{{ c.name }}</li>
<li>{{ c.ects }}</li>
<li>{{ c.description }}</li>
<li>{{ c.year }}</li>
<li>{{ c.semester }}</li>
<li><ul>
{% for t in c.teacher.all %}
<li>{{ t.name }} {# or whatever else you want to display #}</li>
{% endfor %}
</ul></li>
{% endfor %}
</ul>
还有一个旁注:由于教师课程是M2M,因此给该字段赋予复数名称会更方便(和通常做法):Course.teachers