2012-05-15 37 views
0

我有我用它來生成一個動態菜單和當前的應用程序,整個網站的列表的自定義背景處理器:Django的緩存中的自定義背景處理器

from portal.models import * 

def base_items(request): 
    return { 
     ... 
     'app_items': App.objects.filter(isonline=True), 
     'menu_items': MainMenu.objects.all().order_by('position'), 
    } 

編輯:

我的模板(請注意,許多這些URL是Django框架之外,具體費用取決於語言因此,有必要將其硬編碼到數據庫字段:

<ul class="menu"> 
      {% for item in menu_items %} 
       {% if LANGUAGE_CODE = "en-us" %} 
       <li><a title="{{ item.title_en }}" href="{{ item.url_en }}">{{ item.title_en }}</a> 
        <ul> 
        {% for subitem in item.submenu_set.all %} 
         <li><a title="{{ subitem.title_en }}" href="{{ subitem.url_en }}">{{ subitem.title_en }}</a></li> 
        {% endfor %}   
        </ul> 
       </li> 
        {% else %} 
       <li><a title="{{ item.title_es }}" href="{{ item.url_es }}">{{ item.title_es }}</a> 
        <ul> 
        {% for subitem in item.submenu_set.all %} 
       <li><a title="{{ subitem.title_es }}" href="{{ subitem.url_es }}">{{ subitem.title_es }}</a></li> 
        {% endfor %}   
        </ul> 
       </li> 
       {% endif %} 
      {% endfor %}  
      </ul> 

我的問題是 - 我怎麼能緩存這些結果,哪些變化不是很頻繁?

我已經嘗試了@cache_page修飾器,但是我可以看到我的頁面仍然訪問菜單項對象的數據庫。

任何幫助非常感謝。

回答

2

您可以使用django low level cache API。請注意,您可能需要cast the querysets to list

,你可以使用這些查詢集的cache the template fragment,因爲querysets are lazy

+0

嗯。我嘗試過使用模板緩存,但並不尊重語言狀態。請參閱編輯。 –

+3

通過將語言傳遞給{%cache%} templatetag,可以針對當前語言緩存模板片段。像這樣: '{%cache 600 welcome LANGUAGE_CODE%} {%trans「歡迎來到example.com」%} {%endcache%}' – fest

0

嘗試lamdas表達式返回到您的模板:

'app_items': lambda: App.objects.filter(isonline=True), 

這樣,它不會被編譯/緩存和工作動態。