2010-12-22 61 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()的第三个参数。这可以确保在避免大多数数据库调用的同时,缓存将每隔一段时间刷新一次,以便在不重新启动应用程序的情况下使用新的停用词。