【发布时间】:2023-03-09 06:17:01
【问题描述】:
我有一个查询集,只需要根据特定用户提供的条件以特定方式进行过滤。
# 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 脚本中(而不是解释器),但我收到“未定义名称”错误。一些搜索表明它可能是声明错误
queryset = Spot.objects.values()
所以我已经尝试过使用其他变体,例如
queryset = Spot.objects.filter()
queryset = Spot.objects.all()
queryset = Spot.objects()
但它们似乎都不起作用。
编辑:这是我的models.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 *
导入所有内容,因为我在脚本中也有查询访问相同的数据库(但不同的表),它们工作得非常好,所以我相对确定这不是导入问题。
【问题讨论】:
-
我可以看看你的 models.py 声明吗?
-
什么名称未定义?与 Python 中的任何东西一样,您需要先导入一个东西才能使用它;这与 Django 或在脚本中执行此操作无关。
-
请从您的标题中删除“已解决”并发布您自己的解决方案作为正确答案。
标签: python django django-queryset