第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

在模板中使用 for 循環(huán)顯示多個(gè)動(dòng)態(tài)對(duì)象

在模板中使用 for 循環(huán)顯示多個(gè)動(dòng)態(tài)對(duì)象

蕪湖不蕪 2023-09-19 14:34:30
總結(jié)一下,我的數(shù)據(jù)庫結(jié)構(gòu)是這樣的:test  |_ question      |_ choice      |_ choice      |_ choice  |_ question      |_ choice      |_ choice      |_ choice現(xiàn)在我想在一個(gè)頁面上顯示每個(gè)問題的所有選擇。我的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)所以從技術(shù)上來說,如果我有兩個(gè)問題,我的data問題會(huì)是這樣的:{...'choices_1': ...'choices_2': ......}現(xiàn)在,我的問題是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 %}它只是破壞了整個(gè)事情。我對(duì) Django 比較陌生,所以請(qǐng)?jiān)徫业奶煺?。我怎樣才能解決這個(gè)問題?多謝!
查看完整描述

1 回答

?
蕭十郎

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊

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


您只需要在模板中執(zhí)行以下操作:


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

關(guān)鍵部分是question.choice_set.all;Django 自動(dòng)構(gòu)建反向關(guān)系訪問器。


查看完整回答
反對(duì) 回復(fù) 2023-09-19
  • 1 回答
  • 0 關(guān)注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)