如何访问 Django 模板中的字典元素? [英] How to access a dictionary element in a Django template?

查看:40
本文介绍了如何访问 Django 模板中的字典元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印出每个选项获得的票数.我在模板中有此代码:

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 只是一个字典,而 choices 是一个模型对象.

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,因为我不确定它是否会预先缓存属性并仅为该属性创建一个子选择,或者它是否会迭代/on-demand 运行查询以计算投票计数.但是,如果它生成了严重的查询,您始终可以使用自己收集的数据填充视图中的属性.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆