2012-07-28 64 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