Django全局查询集 [英] Django global queryset

查看:54
本文介绍了Django全局查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在django应用程序中有一个全局变量,该变量存储对象的结果列表,供以后在某些函数中使用,并且我不想再对queryset求值一次,我这样做是这样的:

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) ...

这对我来说似乎可以,但是问题是syncdb和test命令抛出异常:

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?

推荐答案

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

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.

这篇关于Django全局查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆