如何在django模板中访问字典元素? [英] how to access dictionary element in django template?
问题描述
{%在选择中选择%}
{{choice。 choice}} - {{votes [choice.id]}}< br />
{%endfor%}
它引发了一个异常,此消息无法解析余数
为了回应/扩展Jeff的评论,我认为你应该瞄准的只是你的Choice课程中的一个属性它计算与该对象相关联的投票数:
class Choice(models.Model):
text = models .CharField(max_length = 200)
def calculateVotes(self):
return Vote.objects.filter(choice = self).count()
vote =财产(calculateVotes)
然后在您的模板中,您可以执行以下操作:
{%在选择中选择%}
{{choice.choice}} - {{choice.votes}}< br />
{%endfor%}
模板标签是IMHO对此解决方案有点过分,但它也不是一个可怕的解决方案。 Django中的模板的目标是将您与模板中的代码隔离开,反之亦然。
我会尝试上面的方法,看看ORM产生的SQL是什么,因为我不确定我的头顶,如果它会预先缓存属性,只需为该属性创建一个子选择,或者它将迭代/点播运行查询来计算投票数。但是,如果它产生残酷的查询,您可以随时使用自己收集的数据填充视图中的属性。
I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object.
{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
it raises an exception with this message "Could not parse the remainder"
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 %}
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.
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屋!