簡體   English   中英

如何在 django views.py 中的單個變量或列表中存儲多個值?

[英]How do I store multiple values in a single variable or list in django views.py?

這是我的 views.py

@login_required
def appsc(request):

    allapplied = Applied_Scholarships.objects.filter(user_id = request.user.id)
    for applied in allapplied.iterator():
        print('hi')
        sch_id = applied.scholarship_id
        queryset = ScholarshipDetails.objects.filter(id = sch_id)
        print(queryset)
        context = {"object_list":queryset}

    return render(request,'applied-scholarships.html',context)

在這里,我需要檢查學生申請的獎學金。 為此,我從Applied_Scholarship表中過濾了條目。 現在,我獲取了Scholarship_id並過濾了ScholarshipDetails表中的條目,以便獲得獎學金的名稱和其他詳細信息。

現在如何防止object_list被覆蓋? 這段代碼只給了我 1 個獎學金而不是 2 個獎學金的價值。

這是我的模板:

            <table class="table mb-0">
                <tr>
                    <th>Scholarship name</th>
                    <th>End Date</th>
                    <th>Status</th>
                    <th></th>
                    <th></th>
                </tr>
                {% for instance in object_list %}
                    <tr>
                        <td>{{instance.name}}</td>
                        <td>{{instance.end_date}}</td>
                        <td>{{applied.status}}</td>
                        <td><a href = "government/home">{{schdets.link}}</a></td>
                    </tr>
                {% endfor %}
            </table>

我需要使用列表嗎? 如果是,那么如何?

為了不覆蓋 for 循環內的變量,您可以執行以下操作:

list_ = []
for x in items:
    list_.append(x.something)
context = {'object_list': list_}

但不是循環遍歷allaplied並獲取ScholarshipDetailsid ,您可以一次性獲取所有信息,例如:

sch_ids = [x.scholarschip_id for x in allapplied.iterator()]
queryset = ScholarshipDetails.objects.filter(id__in=sch_ids)

您需要較少的數據庫查詢,並且不會覆蓋您的變量。

此外:我猜你的模型有一個OneToOne -relation,因此您可以使用select_related直接讓你的細節,而獲取的Applied_Scholarships -instances。 然后你可以去掉第二個filter ,只對細節模型使用相關字段,例如applied.details (確切名稱取決於你的模型設計)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM