【问题标题】:How do I store multiple values in a single variable or list in django views.py?如何将多个值存储在 django views.py 的单个变量或列表中?
【发布时间】:2020-03-23 09:57:53
【问题描述】:

这是我的意见.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>

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

【问题讨论】:

    标签: python django list view


    【解决方案1】:

    为了不覆盖 for 循环中的变量,请执行以下操作:

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

    但不是循环遍历allaplied 并为ScholarshipDetails 获取id,您可以一次获得所有内容,例如:

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

    您需要更少的数据库查询,并且不会覆盖您的变量。

    此外:我猜你的模型有一个OneToOne-relation,所以你可以在获取Applied_Scholarships-instances 时使用select_related 直接获取你的详细信息。然后你可以去掉第二个filter,只使用相关字段作为细节模型,例如applied.details(具体名称取决于您的模型设计)。

    【讨论】:

    • 当我尝试将查询集附加到列表中时,它给了我一个错误消息“附加需要一个列表对象但收到了一个 ScholarshipDetails”。如何将其转换为列表?
    • @waesrgd 确保您拥有list_,而不是list。答案中有错字。
    猜你喜欢
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多