【发布时间】:2021-12-30 00:21:31
【问题描述】:
所以我能够弄清楚如何将字典键和值解包到 HTML 模板中,但是如果字典值是 QuerySet,我对如何解包有点困惑。例如,我将给定用户的所有时间段传递到字典中。如何解包每个时间段的TimeSlot QuerySet的属性,例如开始时间和结束时间?
这是我的 HTML 模板:
<table>
{% for key, value in user_info.items %}
{% for key2,value2 in value.items %}
<tr>
<td>{{key2}}</td>
<td>{{value2}}<td>
</tr>
{% endfor %}
<br>
{% endfor %}
</table>
views.py 中的函数
def check_food_availibility(request):
food = FoodAvail.objects.all()
timeslots = TimeSlot.objects.all()
users_dict = {}
for i in range(len(user_info)):
user = {
"author": None,
"food_available": None,
"description": None,
"timeslot": None
}
user["author"] = user_info[i].author.username
user["food_available"] = user_info[i].food_available
user["description"] = user_info[i].description
if TimeSlot.objects.filter(time_slot_owner=user_info[i].author):
user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author)
users_dict[user_info[i].author.username] = user
return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict})
【问题讨论】:
-
您认为
user_info来自哪里?你能添加你的模型吗?您不需要创建字典并对其进行动态迭代,您知道它是键,因此您可以显式使用它们
标签: python python-3.x django