Django 全局查询集

标签 django django-models

我想在我的 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")

我不知道如何摆脱这个,可能是我走错了路?

最佳答案

听起来 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() 的第三个参数。 .这可确保在您避免大多数数据库调用的同时,缓存将不时刷新,以便可以在不重新启动应用程序的情况下使用新的停用词。

关于Django 全局查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4513600/

相关文章:

python - 用日期排序查询集

django - django 上的替代形式库,例如 sprox、formalchemy

python - 生成假数据以填充数据库

javascript - “请求 header 字段不允许授权”错误 - Tastypie

python - 如何定义一个引用自身的 Django 模型?

django - 在 Django 1.7 迁移之前运行 South 迁移的推荐方法是什么?

django - pre_delete 信号在特定目录中不起作用

python - 内容未渲染错误: The response content must be rendered before it can be iterated over

python - 使用 django 编码字符串作为 django 信号的发送者

python - 如何在 Django 中从 JSONField 添加/删除数据