如何从Django模板中保存查询,以便只执行一次?

时间:2010-12-30 04:58:26

标签: django django-templates

有没有办法只在模板中保存查询,因此只执行一次?

我有以下模板:

{% for list in lists %}
<li>
  {{ list }} <span>{{ list.num_items }} item{{ list.num_items|pluralize }}</span>
</li>
{% endfor %}

num_items是列表模型中的以下方法:

    def num_items(self):
      return self.item_set.all().count()

这两次查询num_items。是否有可能只这样做一次?

2 个答案:

答案 0 :(得分:3)

使用with。来自文档:

{% with business.employees.count as total %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

答案 1 :(得分:0)

不使用方法,而是使用缓存结果的属性。