2013-01-01 187 views
1
從模型特定數據

型號:django的顯示模板

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-> exercise1,subject2-> exercise1,subject3-> exercise1,subject4-> exercise2等) 我想顯示3個表格一個模板和每個表格將只顯示tr /主題相應的表/練習。我嘗試了{%if ... in ...%},但也許我應該在視圖中執行一些功能。

回答

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 %} 
+0

不應s_field.name.e代替e_field? – Chris

+0

也許。我從你的例子中複製了它。 – hayavuk