[英]How do I store multiple values in a single variable or list in django views.py?
Here is my 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)
Here, I need to check the applied scholarships of a student.在这里,我需要检查学生申请的奖学金。 So for that, I have filtered the entries from the Applied_Scholarship table.为此,我从Applied_Scholarship表中过滤了条目。 Now from that, I took scholarship_id and filtered the entries in ScholarshipDetails table so that I get the name and other details of the scholarship.现在,我获取了Scholarship_id并过滤了ScholarshipDetails表中的条目,以便获得奖学金的名称和其他详细信息。
Now how do I prevent object_list to get overridden?现在如何防止object_list被覆盖? This code gives me value of only 1 scholarship instead of 2.这段代码只给了我 1 个奖学金而不是 2 个奖学金的价值。
Here is my template:这是我的模板:
<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>
Do I need to use list?我需要使用列表吗? If yes, then how?如果是,那么如何?
For not overwriting a variable inside a for-loop you do following:为了不覆盖 for 循环内的变量,您可以执行以下操作:
list_ = []
for x in items:
list_.append(x.something)
context = {'object_list': list_}
But instead of looping over allaplied
and getting the id
for ScholarshipDetails
you could get all at once, like:但不是循环遍历allaplied
并获取ScholarshipDetails
的id
,您可以一次性获取所有信息,例如:
sch_ids = [x.scholarschip_id for x in allapplied.iterator()]
queryset = ScholarshipDetails.objects.filter(id__in=sch_ids)
You need less database queries and you don't overwrite your variable.您需要较少的数据库查询,并且不会覆盖您的变量。
Furthermore: I guess your models have a OneToOne
-relation, so you could use select_related to directly get your details while fetching the Applied_Scholarships
-instances.此外:我猜你的模型有一个OneToOne
-relation,因此您可以使用select_related直接让你的细节,而获取的Applied_Scholarships
-instances。 Then you could get rid of the second filter
and just use the related field for the details models, eg applied.details
(exact name depends on your model-design).然后你可以去掉第二个filter
,只对细节模型使用相关字段,例如applied.details
(确切名称取决于你的模型设计)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.