Django Global Query Set

I would like to have a global variable in my django application that stores the resulting list of objects that I later use in some functions, and I do not want to evaluate the request in more detail again, 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) ...

It seems to me that this is normal, but the problem is that the syncdb and test command throws an exception:

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

I do not know how to get rid of this, maybe I'm wrong?

+3
source share
2 answers

Do not initialize queries in the global scope. Bind Noneto a name, then write a function that first checks to see Noneif it has a value , and if so it generates data, and then returns the value.

+1

, , StopWord, , syncdb .

django 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(). , , , , - .

+1

Source: https://habr.com/ru/post/1781740/


All Articles