模型:
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 %}
它只显示每个现有主题的所有程序,我只想看到一个与程序相关的主题。