我有以下型号:
class Student(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
skypeid = models.CharField(max_length=100)
email = models.EmailField(max_length=75)
youtubechannel = models.URLField(max_length=200)
def __unicode__(self):
return self.surname
class LanguageKnowledge(models.Model):
LOW = 'LOW'
MEDIUM = 'MED'
ADVANCED = 'ADV'
EXPERT = 'EXP'
LANGUAGE_KNOWLEDGE_CHOICES =(
(LOW, 'LOW'),
(MEDIUM, 'Medium'),
(ADVANCED,'Advanced'),
(EXPERT, 'Expert'),
)
student = models.ForeignKey(Student)
language = models.ForeignKey(Language)
grammar = models.CharField(max_length=3, choices=LANGUAGE_KNOWLEDGE_CHOICES)
reading = models.CharField(max_length=3, choices=LANGUAGE_KNOWLEDGE_CHOICES)
speaking = models.CharField(max_length=3, choices=LANGUAGE_KNOWLEDGE_CHOICES)
writing = models.CharField(max_length=3, choices=LANGUAGE_KNOWLEDGE_CHOICES)
def __unicode__(self):
return u'%s : %s' % (self.student, self.language)
然后是以下视图
def student(request, student_id):
try:
studentdetails = Student.objects.get(pk=student_id)
languageknowledge_list = LanguageKnowledge.objects.filter(student__id__exact=student_id)
except Student.DoesNotExist:
raise Http404
return render(request, 'broker/student.html',
{'studentdetails': studentdetails,
'languageknowledge_list': languageknowledge_list})
但是,以下模板未列出languageknowledge_list中存在的不同语言。作为一个更一般的问题,我如何通过模板列出涉及一对多关系的查询集(例如,说几种语言的学生)?
{% block content %}
<ul>
{% for languageknowlege in languageknowledge_list %}
<li>{{ languageknowledge.language }}, h2 got it,</li>
{% endfor %}
</ul>
{% endblock %}
答案 0 :(得分:1)
您在languageknowledge
变量的模板中拼写错误。
更改此行:
{% for languageknowlege in languageknowledge_list %}
<li>{{ languageknowledge.language }}, h2 got it,</li>
要:
{% for languageknowledge in languageknowledge_list %}
<li>{{ languageknowledge.language }}, h2 got it,</li>
请注意,最好使用至少具有拼写检查功能的好ide
,并在组合时将变量名称与_
分开,例如使用language_knowledge
代替{{ 1}}帮助拼写检查器更好地检测拼写错误。