Django全局查询集

4
我希望在我的Django应用程序中有一个全局变量,可以存储结果对象列表,并在一些函数中使用。我不想评估查询集超过一次,所以我这样做:
from app.models import StopWord

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

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

这对我来说看起来没问题,但问题是syncdb和test命令会抛出异常:

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

我不知道该如何摆脱这个问题,可能我走了一条错误的路线?

你的应用程序是否在 settings.INSTALLED_APPS 列表中? - Seth
2个回答

2

看起来StopWord所在的应用程序没有出现在已安装的应用程序设置中,或者您还没有运行syncdb生成表。

使用Django缓存框架可以模拟存储“全局值”。

# 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()。这样可以确保在避免大部分数据库调用的同时,缓存会定期刷新,以便可以使用新的停用词而无需重新启动应用程序。

1
不要在全局范围内初始化查询。将None绑定到名称,然后编写一个函数,首先检查该值是否为None,如果是,则生成数据,然后返回该值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接