2012-07-28 67 views
0

我注意到我的django代码经常使用完全相同的查询来调用我的数据库。减少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 %}循环中使用第三。

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

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

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

编辑:使用with的作品,但它有可能避免数据库点击自定义过滤器?

回答

2

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

{% with item.listing as item_listing %} 
    {% if item_listing %} ... {% endif %} ... etc ... 
{% endwith %} 
+0

'with'限于只在一个'block'中使用吗? – Joey 2012-07-28 23:46:34

+0

NVM。在块元素外使用'with'工程。 – Joey 2012-07-29 15:26:02