如何访问Django模板中的dictionary元素?

2024-06-16 10:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印出每个选择得到的票数。我有一个模板中的代码:

{% for choice in choices %}
    {{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}

votes只是一个字典,而choices是一个模型对象。

它引发此消息的异常:

"Could not parse the remainder"

Tags: 对象代码in模型br模板id消息
3条回答

您可以使用点符号:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup (e.g., foo["bar"])
  • Attribute lookup (e.g., foo.bar)
  • Method call (e.g., foo.bar())
  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.

choices = {'key1':'val1', 'key2':'val2'}

这是模板:

<ul>
{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
{% endfor %}
</ul>

基本上,.items是一个Django关键字,它将字典拆分成一个由(key, value)对组成的列表,这与Python方法.items()非常相似。这允许在Django模板中对字典进行迭代。

根据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)

然后在模板中,可以执行以下操作:

    {% for choice in choices %}
            {{choice.choice}} - {{choice.votes}} <br />
    {% endfor %}

模板标签对于这个解决方案来说有点过分了,但它也不是一个糟糕的解决方案。Django中模板的目标是将您与模板中的代码隔离开来,反之亦然。

我会尝试上面的方法,看看or m生成了什么SQL,因为我不确定ORM是否会预先缓存属性并为属性创建一个子选择,或者它是否会迭代/按需运行查询来计算投票数。但是,如果它生成了糟糕的查询,您可以始终用自己收集的数据填充视图中的属性。

相关问题 更多 >