2010-12-22 66 views
3

我想在我的django應用程序中有一個全局變量,用於存儲後來在某些函數中使用的對象的結果列表,我不想多次評估queryset,我這樣做:Django全局查詢集

from app.models import StopWord 

a = list(StopWord.objects.values_list('word', flat=True)) 
... 

def some_func(): 
    ... (using a variable) ... 

這似乎沒給我,但問題是,執行syncdb和測試命令拋出一個異常:

django.db.utils.DatabaseError: (1146, "Table 'app_stopword' doesn't exist") 

我不知道如何擺脫這一點,可能是我在錯誤的方法?

+0

你的應用列在`settings.INSTALLED_APPS`中嗎? – Seth 2010-12-22 21:01:54

+0

是的,它是那裏 – dragoon 2010-12-22 21:26:18

回答

1

請勿在全局範圍內初始化查詢。將None綁定到名稱上,然後編寫一個函數,首先檢查值是否爲None,如果是,則生成數據,然後返回該值。

1

聽起來像StopWord是其中一部分的應用程序不是在您已安裝的應用程序設置中,或者您沒有運行syncdb來生成表格。

通過使用django cache framework可以模擬存儲'全局值'。

# there is more to it then this - read the documentation 
# settings.py needs to be configured. 

from django.core.cache import cache 

class StopWord(models.Model): 
    ... # field definitions 

    @classmethod 
    def get_all_words(cls): 
     key = 'StopWord.AllCachedWords.Key' 
     words = cache.get(key) 
     if words is None: 
      words = list(StopWord.objects.values_list('word', flat=True)) 
      cache.set(key, words) 
     return words 

#elsewhere 
from app.models import StopWord 

for word in StopWord.get_all_words(): 
    # do something 

上面還處理了一種緩存失效。您的設置應該設置默認超時時間,或者您可以將自己的超時設置爲cache.set()的第三個參數。這可以確保在避免大多數數據庫調用的同時,緩存將每隔一段時間刷新一次,以便在不重新啓動應用程序的情況下使用新的停用詞。