型号:
class Exercise (models.Model):
name_e = models.CharField(max_length=50)
class Subject (models.Model):
name_s = models.CharField(max_length=50)
exercise = models.ForeignKey(Exercise)
查看:
exercise_all = Exercise.objects.all()
subject_all = Subject.objects.all()
我的SQL表包含通过ForeignKey连接的主题和练习
我将视图变量作为上下文传递给模板:
{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
{% for s_field in subject_all %}
<tr><td>{{ e_field.name_e }}</td></tr>
{% endfor %}
</table>
{% endfor %}
如果我有,比方说,3种类型的练习和10个与练习相关的主题(subject1-&gt; exercise1,subject2-&gt; exercise1,subject3-&gt; exercise1,subject4-&gt; exercise2等) 我想在模板中显示3个表,每个表只显示对应于表/练习的tr /主题。我尝试使用{%if ... in ...%},但也许我应该在视图中执行某些功能。
答案 0 :(得分:2)
在这种情况下,您应该能够说:
{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
{% for s_field in e_field.subject_set.all %}
<tr><td>{{ e_field.name_e }}</td></tr>
{% endfor %}
</table>
{% endfor %}