减少django db调用

时间:2012-07-28 21:05:29

标签: django django-models django-templates

我注意到我的django代码经常使用完全相同的查询来调用我的数据库。

我知道当我真正需要在页面上显示数据或进行评估时,会发生数据库命中。但是,我的模板代码如下所示:

模板:

{% if item.listing %}
        {{ item.name }} text <strong>{{ item.listing|lowestprice }}</strong>  more text
{% else %}
        {{ item.name }} even more text
{% endif %}
     ....
{% for listed_item in item.listing %}
     ....
{% endfor %}

自定义过滤器:

def lowestprice(value):
   try:
      val = unicode(value[0].price) + unicode(value[0].symbol)
      return val
   except:
      return "not available"

此代码三次点击我的数据库。首先在我的自定义过滤器上的模板{% if .. %}上排名第二,在{% for %}循环中排在第三位。

listing是我的模型类的一种方法,它返回一个带有一些非常昂贵的连接的原始SQL查询集。

def listing(self):
    return Universe.objects.raw("ONE HELL OF A QUERY")

如何减少我的代码只能打到数据库一次?

编辑:使用with有效,但是有可能避免自定义过滤器上的数据库命中吗?

1 个答案:

答案 0 :(得分:2)

您应该使用with进行一次昂贵的查询并将其存储在上下文中。

{% with item.listing as item_listing %}
   {% if item_listing %} ... {% endif %} ... etc ...
{% endwith %}
相关问题