我有一个查询集,它只需要根据用户提供的特定条件以特定的方式进行过滤。在
# construct the base queryset first
queryset = Spot.objects.values()
# zero is the default value,
# so only need to filter if an actual value is provided
if mindist > 0:
queryset = queryset.filter(distance >= mindist)
if maxdist > 0:
queryset = queryset.filter(distance <= maxdist)
if starttime != 0:
queryset = queryset.filter(unix_time >= starttime)
if endtime != 0:
queryset = queryset.filter(unix_time <= endtime)
objects_list = list(queryset)
return objects_list
实际上,我试图复制Django文档中提到的功能https://docs.djangoproject.com/en/1.8/topics/db/queries/#querysets-are-lazy
但是在.py脚本(而不是解释器)中使用条件,但是我得到了一个“Name is not defined”错误。一些搜索表明,这可能是
^{pr2}$所以我试过用其他变体,比如
queryset = Spot.objects.filter()
queryset = Spot.objects.all()
queryset = Spot.objects()
但似乎都不管用。在
编辑:这是我的模型.py在
class Spot(models.Model):
spot_id = models.IntegerField(db_column='Spot_ID', primary_key=True) # Field name made lowercase.
unix_time = models.IntegerField(db_column='UNIX_time', blank=True, null=True) # Field name made lowercase.
distance = models.IntegerField(db_column='Distance', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'SPOT'
进一步澄清。无论哪个过滤器在初始值之后出现错误Spot.objects.values(). 例如在上面的一个例子中
queryset = queryset.filter(distance >= mindist)
是第一个,错误将指向未定义距离的那条线。我试过改变顺序,例如
queryset = queryset.filter(unix_time <= endtime)
首先是。但是我得到了同样的错误,但是这次是用unix_time'定义的。在
我把名字仔细核对了一遍,都是正确的。我用的是
from .models import *
要导入所有内容,因为我在脚本中也有查询,这些查询访问的是同一个数据库(但不同的表),运行得非常好,所以我相对确定这不是导入问题。在
已解决
所以我终于发现了问题所在。显然,filter()无法识别标准比较运算符,如>;=和<;=。在
相反,它使用字段查找来模拟sqlwhere子句。所以不是
我应该做的
^{pr2}$感谢所有试图帮助的人,我希望这对任何遇到同样问题的人都有用。在
您需要将
queryset = Spot.objects
替换为queryset = Spot.objects.values()
您还需要导入您的Spot model
,以防尚未导入。在相关问题 更多 >
编程相关推荐