开发者

How can I save a query from within a Django template so it is only preformed once?

Is there a way to only save a query from within a template so it is only preformed once?

I have the following template:

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

And num_items is the following method in the list model:

    def num_items(self):
      return self.item_set.all()开发者_如何学编程.count()

This queries num_items twice. Is it possible to only do so once?


Use with. From the docs:

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


Instead of using a method, use a property that caches the result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜