Python Django,努力创建动态列表

Python Django, struggling to create a dynamic list

我想在我的网站上创建一个部分,其中每个主题都可以找到相应的过去论文的链接,但我很难获得任何输出。寻找想法:

我的views.py:

def index(request):
    subjects = Subject.objects.all()
    context = {'subjects': subjects}
    return render(request, 'alevelspastpapers/index.html', context=context)

我的models.py:

class Subject(models.Model):
    subject = models.CharField(max_length=30)
    def __str__(self):
        return self.subject

class past_paper(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    exam_date = models.DateField('Examination Date')
    paper_number = models.IntegerField('Paper Number: ')
    paper_urllink = models.TextField()
    markscheme_urllink = models.TextField()
    solved_paperslink = models.TextField(null=True)
    def __str__(self):
        return f"{self.subject} Paper {self.paper_number}, {self.exam_date}"

我的html内容:

{% if subjects %} {% for subject in subjects %}
      <p>{{ subject.subject }}</p>
      {% for papers in subject.subject.past_papers_set.all %}
      <p>{{ papers.paper_urllink }}</p>
      {%endfor%} {% endfor %} {% endif %}

{% for papers in subject.subject.past_papers_set.all %}替换为{% for papers in subject.past_papers_set.all() %}

试试这个:

{% for subject in subjects %}
    <p>{{ subject.subject }}</p>
    {% for past_paper in subject.past_paper_set.all %}
       <p> {{ past_paper.paper_urllink }} </p>
    {% endfor %}
{% endfor %}

为了获得更好的性能,您可以使用 select_related 仅在一个查询中获取相关对象,如下所示:

def index(request):
    subjects = Subject.objects.all().select_related()
    # rest of your code