Home > Software engineering >  Python Django, struggling to create a dynamic list
Python Django, struggling to create a dynamic list

Time:12-31

I want to create a section on my site, where for each subject, links to corresponding past papers can be found, but I am struggling to get any output. Looking for ideas:

My views.py:

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

My 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}"

My html content:

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

CodePudding user response:

Try this:

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

For better performance you can use select_related which fetch related objects in just one query like this:

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

CodePudding user response:

Replace {% for papers in subject.subject.past_papers_set.all %} with {% for papers in subject.past_papers_set.all() %}

  • Related