我想在我的 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 缓存框架 http://docs.djangoproject.com/en/dev/topics/cache/.
# 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()
。这确保了在避免大多数数据库调用的同时,缓存会经常刷新,以便可以使用新的停用词而无需重新启动应用程序。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)