亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在模板中使用 for 循環顯示多個動態對象

在模板中使用 for 循環顯示多個動態對象

蕪湖不蕪 2023-09-19 14:34:30
總結一下,我的數據庫結構是這樣的:test  |_ question      |_ choice      |_ choice      |_ choice  |_ question      |_ choice      |_ choice      |_ choice現在我想在一個頁面上顯示每個問題的所有選擇。我的views.py:def index(request):    data = {        'greeting': 'Welcome User!',        'form_test': forms.TestForm,        'form_question': forms.QuestionForm,        'form_choice': forms.ChoiceForm,        'test': models.Test.objects.get(pk=1),        'questions': models.Question.objects.filter(test_id__exact=1),    }    questions = models.Question.objects.filter(test_id=1)    for question in questions:        data['choices_{}'.format(question.id)] = models.Choice.objects.filter(question_id=question.id)    print(data)    return render(request, 'et_app/index.html', context=data)所以從技術上來說,如果我有兩個問題,我的data問題會是這樣的:{...'choices_1': ...'choices_2': ......}現在,我的問題是choices在模板上顯示這些。我試過:{% for question in questions %}    <h4>Q: {{ question.content }}</h4>    <p>Choices:</p>    <ul class="list-group">        {% for choice in 'choices_{}'.format(question.id) %}            <li class="list-group-item">{{ choice.content }}</li>        {% endfor %}    </ul>{% endfor %}它只是破壞了整個事情。我對 Django 比較陌生,所以請原諒我的天真。我怎樣才能解決這個問題?多謝!
查看完整描述

1 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

您不需要首先手動構建選擇上下文變量(部分data['choices_{}'.format(question.id)])。


您只需要在模板中執行以下操作:


{% for question in questions %}

? ? <h4>Q: {{ question.content }}</h4>


? ? <p>Choices:</p>

? ? <ul class="list-group">

? ? ? ? {% for choice in question.choice_set.all %}

? ? ? ? ? ? <li class="list-group-item">{{ choice.content }}</li>

? ? ? ? {% endfor %}

? ? </ul>

{% endfor %}

關鍵部分是question.choice_set.all;Django 自動構建反向關系訪問器。


查看完整回答
反對 回復 2023-09-19
  • 1 回答
  • 0 關注
  • 91 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號