Django forloop inside forloop in Template

Question:

hello iam trying to make Dropdown Menu in Navbar with querysets. I was trying to make it with two querysets send to html template ( "stages","questions") that are related to each other by key (id , stage_id), but i cant figured out why forloops cant work together. My second try was with passing data in json to javascript and make it with js QuerySelector, but django querysets are not JSON serializable. Any suggestions how to make it please ?

views.py

def edit_pages(request, gameid):
    stages = Stage.objects.filter(game_id=gameid)
    print(stages)
    questions = []
    for st in stages:
        questions = chain(questions,Question.objects.filter(stage_id=st.id))
    print(questions)
        
    return render(request, "homeSuperuser/edit_pages.html",{'stages': stages, 'questions': questions})

html

<body>
        <div class="topnav">
            {% for st in stages %}
                <div class="dropdown">
                    <button class="dropbtn">{{st.stage_name}}</button>
                    <div class="dropdown-content">
                        {% for qs in questions %}
                            {% if qs.stage_id == st.id %}
                                <a href="#">{{qs.question_name}}</a>
                            {% endif %}
                        {% endfor %}
                    </div>
                </div>
            {% endfor %}
        </div>
    </body>
Asked By: Noobie

||

Answers:

Define a model method as follows

class Stage(models.Model):
    name = models.CharField(max_length=128)

    def get_questions(self):
        return Question.objects.filter(stage=self)

    def __str__(self):
        return str(self.name)


class Question(models.Model):
    stage = models.ForeignKey(Stage, on_delete=models.PROTECT, related_name="questions")
    name = models.CharField(max_length=128)

    def __str__(self):
        return str(self.name)

Now you can loop them in the template as follows

{% for st in stages %}
    <div class="dropdown">
        <button class="dropbtn">{{st.name}}</button>
        <div class="dropdown-content">
            {% for qs in st.get_questions %}
              <a href="#">{{qs.name}}</a>
            {% endfor %}
        </div>
    </div>
{% endfor %}
Answered By: ANFAS PV
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.