型号:
class Program (models.Model):
name = models.CharField(max_length=70)
add = models.DateTimeField(auto_now=True)
class Subject (models.Model):
s_name = models.CharField(max_length=50)
program = models.ForeignKey(Program)
s_add = models.DateTimeField(auto_now=True)
在数据库中,我已经添加了相同的行,例如:
app_program表中的:
id | name | add
1 | Program1 | some date
2 | Program2 | some date
3 | Program3 | some date
在app_subject中:
id | s_name | program | add
1 | subject1 | 1 | some date
2 | subject2 | 2 | some date
3 | subject3 | 1 | some date
4 | subject4 | 2 | some date
5 | subject5 | 3 | some date
现在在我的模板中,我想在for循环中显示数据,如下所示:
1. Program1
1. subject1
2. subject3
2. Program2
1. subject2
2. subject4
3. Program3
1. subject5
我不知道在我的观点和模板中放什么。我试过了:
from app.models import Program, Subject
program_all = Program.objects.all()
subject_all = Subject.objects.all()
然后我将它作为上下文变量等传递给模板,当我在模板中使用它时:
{% for field in program_all %}
{{ forloop.counter }}. {{ field.name }}
{% for field2 in subject_all %}
{{ field2.s_name }}
{% endfor %}
{% endfor %}
它只显示所有现有主题的所有程序,我希望只看到与程序相关的主题。
答案 0 :(得分:2)
你需要这个:
{% for field in program_all %}
{{ forloop.counter }}.{{ field.name }}
{% for subject in field.subject_set.all %}
{{ forloop.counter }}. {{ subject.s_name }}
{% endfor %}
{% endfor %}
在您的模型中建立关系后,您也可以follow it backward。
在这种情况下,对于每个program
,都有一个subject_set
,它是与该程序相关的所有主题。在您的视图或django shell中,它将是这样的:
for p in Program.objects.all():
print 'The program {} has {} subjects:'.format(p,p.subject_set.count())
for subject in p.subject_set.all():
print subject