如何在Django模板中访问字典元素? [英] How to access a dictionary element in a Django template?
问题描述
我想打印出每个选择获得的票数。我在模板中有以下代码:
I would like to print out the number of votes that each choice got. I have this code in a template:
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
投票
只是字典,而选择
是模型对象。
votes
is just a dictionary while choices
is a model object.
此消息引发异常:
"Could not parse the remainder"
推荐答案
要回应/扩展Jeff的评论,我认为您应该针对的只是Choice类中的一个属性,计算与该对象关联的投票数:
To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:
class Choice(models.Model):
text = models.CharField(max_length=200)
def calculateVotes(self):
return Vote.objects.filter(choice=self).count()
votes = property(calculateVotes)
然后在模板中,您可以执行以下操作:
And then in your template, you can do:
{% for choice in choices %}
{{choice.choice}} - {{choice.votes}} <br />
{% endfor %}
模板标签,恕我直言,对于该解决方案来说有点过头了,但不是一个可怕的解决方案。 Django中模板的目标是使您与模板中的代码隔离,反之亦然。
The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.
我会尝试上述方法,看看ORM生成的SQL不是我生成的确保它会预先缓存属性并为该属性创建一个子选择,还是会迭代/按需运行查询以计算投票数,这是我的头上问题。但是,如果它产生了残酷的查询,您总是可以使用自己收集的数据填充视图中的属性。
I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.
这篇关于如何在Django模板中访问字典元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!