You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Jinja模板中使用变量作为字典键的Django开发问题

解决Django模板中调用问题答案字典的语法问题及优化方案

一、模板语法修正

你在模板里的写法错误在于嵌套了模板变量语法,Jinja2中直接使用[]访问字典键即可,不需要额外的{{ }}。正确的循环写法应该是:

{% for answer in answers[question.id] %}
    {{ answer.text }}
{% endfor %}

如果之前用answers[question.id]无效,先排查这两点:

  • 确认视图中answers字典的键是整数类型的question.id,而非字符串(比如若id来自URL参数的字符串类型,需转成int)
  • 确保answers已正确传入模板上下文(比如在视图的render函数里将answers加入context参数)

二、更优的视图传参方案(无需手动构建字典)

手动循环构建字典不仅繁琐,还会引发N+1次数据库查询(每个Question单独查一次Answer)。推荐用Django的prefetch_related预加载关联数据,直接通过Question对象访问关联的Answer集合:

视图代码优化:

# 一次性预加载所有Question对应的Answer,避免多次查询数据库
questions = Question.objects.all().prefetch_related('answer_set')

注:answer_set是Django默认的反向关联名称——如果你的Answer模型外键字段定义了related_name(比如question = models.ForeignKey(Question, related_name='answers', ...)),就替换成对应的related_name值即可。

模板中直接使用:

{% for question in questions %}
    <h3>{{ question.text }}</h3>
    {% for answer in question.answer_set.all %}
        <p>{{ answer.text }}</p>
    {% endfor %}
{% endfor %}

这种方式代码更简洁,还能大幅减少数据库查询次数,提升页面性能,完全不需要手动构建字典。

补充(非推荐方案)

如果一定要保留字典方式,可在视图中将键转为字符串,或在模板里把question.id转为字符串:

{% for answer in answers[question.id|stringformat:"i"] %}
    {{ answer.text }}
{% endfor %}

但该方式远不如prefetch_related优雅高效,不建议使用。

内容的提问来源于stack exchange,提问作者Smurphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:40:41