0

模型:

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

它只显示每个现有主题的所有程序,我只想看到一个与程序相关的主题。

4

1 回答 1

2

你需要这个:

{% for field in program_all %}
  {{ forloop.counter }}.{{ field.name }}
  {% for subject in field.subject_set.all %}
     {{ forloop.counter }}. {{ subject.s_name }}
  {% endfor %}
{% endfor %}

在模型中建立关系后,您也可以向后跟踪它

在这种情况下,对于每个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
于 2012-12-31T20:10:31.757 回答