Django模板输出合并查询集遇问题,求代码修正与模板写法指导
Django项目错误修正与模板编写指导
一、修正others/views.py中的错误
你的视图代码存在两个关键错误:
- Context定义错误:你误用列表语法定义context,Django要求context必须是字典类型,应使用
{}而非[] - 代码缩进错误:
return语句的缩进层级错误,需与函数内其他语句保持一致
另外注意模型中的Charfield要改为CharField(首字母大写),否则会触发字段定义错误。
修正后的完整视图代码:
from itertools import chain from action.models import Action from adventure.models import Adventure def windows_games(request): win_action = Action.objects.filter(os='windows') win_adventure = Adventure.objects.filter(os='windows') combined_list = list(chain(win_action, win_adventure)) # 修正为字典格式的context context = {'combined_list': combined_list} # 修正缩进 return render(request, 'others/os/windows_game.html', context)
二、编写模板正确输出合并后的查询集数据
combined_list是多个游戏对象的列表,不能直接通过{{combined_list.name}}取值,需要用Django模板的for循环遍历每个对象,再输出对应属性:
修正后的others/os/windows_game.html代码:
..... <div class="container"> {% for game in combined_list %} <div class="game-item"> <img src="{{ game.game_pic }}" alt="{{ game.name }}"> <p>{{ game.name }}</p> </div> {% empty %} <p>暂无Windows系统的游戏</p> {% endfor %} </div>
说明:
- 使用
{% for ... %}遍历列表中的每个游戏对象 - 用
{{ game.name }}、{{ game.game_pic }}获取单个对象的属性 {% empty %}分支用于处理列表为空的情况,提升用户体验
内容的提问来源于stack exchange,提问作者GxN Samuel
相关产品推荐
相关产品推荐

