【问题标题】:Django global querysetDjango 全局查询集
【发布时间】:2010-12-22 20:52:41
【问题描述】:

我想在我的 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 中列出?

标签: django django-models


【解决方案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() 的第三个参数。这可确保在您避免大多数数据库调用的同时,缓存会不时刷新,因此可以在不重新启动应用程序的情况下使用新的停用词。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2020-10-26
      • 2017-01-12
      • 2012-04-26
      • 2015-12-12
      • 2013-12-06
      • 2021-07-25
      • 2011-05-16
      • 2021-10-22
      相关资源
      最近更新 更多