Django global queryset

邮差的信 提交于 2021-02-19 03:08:58

问题


I would like to have a global variable in my django app that stores resulting list of objects that I later use in some functions and I don't want to evaluate queryset more that once, i do it like this:

from app.models import StopWord

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

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

This seems ok to me but the problem is that syncdb and test command throw an exception:

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

I don't know how to get rid of this, may be I am on a wrong way?


回答1:


Don't initialize queries in a global scope. Bind None to the name, then write a function that first checks if the value is None and if so generates the data, and then returns the value.




回答2:


It sounds like the app that StopWord is a part of is either not in your installed apps setting, or you haven't run syncdb to generate the table.

Storing a 'global value' can be simulated by using the 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

The above also handles a sort of cache invalidation. Your settings should set a default timeout, or you can set your own timeout as a 3rd parameter to cache.set(). This ensures that while you avoid most database calls, the cache will be refreshed every so often so new stopwords can be used without restarting the application.



来源:https://stackoverflow.com/questions/4513600/django-global-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!