Moh*_*med 170 python django django-templates
我在模板中有这个代码,我想打印出每个选项得到的票数.投票只是字典而选择是模型对象.
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
它引发了一条异常,显示"无法解析余数"
rus*_*spy 268
choices = {'key1':'val1', 'key2':'val2'}
Run Code Online (Sandbox Code Playgroud)
这是模板:
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
基本上,.items是一个Django关键字,它将字典拆分为(键,值)对列表.这允许在Django模板中对字典进行迭代.
Wil*_*elm 172
你可以使用点符号:
点查找可以这样概括:当模板系统遇到变量名中的点时,它会按以下顺序尝试以下查找:
- 字典查找(例如,foo ["bar"])
- 属性查找(例如,foo.bar)
- 方法调用(例如,foo.bar())
- 列表索引查找(例如,foo [2])
系统使用第一个有效的查找类型.这是短路逻辑.
小智 61
为了回应/扩展Jeff的评论,我认为你应该瞄准的只是Choice类中的一个属性,它计算与该对象相关的投票数:
class Choice(models.Model):
text = models.CharField(max_length=200)
def calculateVotes(self):
return Vote.objects.filter(choice = self).count()
votes = property(calculateVotes)
Run Code Online (Sandbox Code Playgroud)
然后在您的模板中,您可以执行以下操作:
{% for choice in choices %}
{{choice.choice}} - {{choice.votes}} <br />
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
模板标签,恕我直言,这个解决方案有点矫枉过正,但它也不是一个可怕的解决方案.Django中模板的目标是使您与模板中的代码隔离,反之亦然.
我会尝试上面的方法,看看ORM生成了什么SQL,因为我不确定它是否会预先缓存属性,只是为属性创建一个子选择,或者它是否会迭代/开启 - 需求运行查询以计算投票计数.但是,如果它生成了残酷的查询,您可以随时使用自己收集的数据填充视图中的属性.
Ned*_*der 22
您需要找到(或定义)'get'模板标签,例如,此处.
标签定义:
@register.filter
def hash(h, key):
return h[key]
Run Code Online (Sandbox Code Playgroud)
它的使用方式如下:
{% for o in objects %}
<li>{{ dictionary|hash:o.id }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
类似于@russian_spy 的回答:
<ul>
{% for choice in choices.items %}
<li>{{choice.0}} - {{choice.1}}</li>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)
这可能适合分解更复杂的字典。
使用字典项目
{% for key, value in my_dictionay.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
小智 6
django_template_filter 过滤器名称get_value_from_dict
{{ your_dict|get_value_from_dict:your_key }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
174752 次 |
| 最近记录: |