我正在使用一个简单的查询集来返回City
中存在的对象。
我的City
模型如下:
class City(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, unique=True)
def __unicode__(self):
return self.name
搜索表单有两个输入,一个是文本框,另一个是选择城市的下拉列表。默认下拉选项为:Please select a city
。最初,我做了以下事情:
def search_page(request):
if 'query' in request.GET and request.GET['query']:
city = request.GET['city']
if city == 'Please select a city':
cit = 'New York'
else:
cit = city
q = request.GET['query']
它只能在纽约搜索。但是,如果Please select a city
是提交时选择的选项,我觉得可以在所有城市进行搜索。为此,我尝试了以下
def search_page(request):
if 'query' in request.GET and request.GET['query']:
city = request.GET['city']
if city == 'Please select a city':
cit = City.objects.all()
else:
cit = city
q = request.GET['query']
然而,这给了我一个错误如下:
ProgrammingError at /search
operator does not exist: character varying = integer
LINE 1: ...yes%') AND "Appname_city"."name" = (SELECT...
返回搜索结果的查询集是:
ct = Classified.objects.filter(Q(name__icontains=q) | Q(subcategory__parent__type__icontains=q) | Q(address__area__icontains=q) | Q(subcategory__name__icontains=q)).filter(active__icontains='yes').filter(address__city__name__exact=cit)
分类是:
class Classified(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=256)
contact_person = models.CharField(max_length=300)
email = models.CharField(max_length=100)
address = models.ForeignKey(Address)
subcategory = models.ForeignKey(Subcategory)
phone_number = models.BigIntegerField(max_length=20, default=0)
secondary_number = models.BigIntegerField(max_length=20, default=0, blank=True)
image = S3DirectField(upload_to='s3direct', blank=True)
NO = 'NO'
YES = 'YES'
APPROVAL = ((NO, 'no'), (YES, 'yes'))
active = models.CharField(choices=APPROVAL, default=NO, max_length=3)
verified = models.CharField(choices=APPROVAL, default=NO, max_length=3)
def __unicode__(self):
return self.name
编辑:添加显示错误的代码行:
ct = paginate.page(1)
分页如下:
paginate = Paginator(ct, 10)
page = request.GET.get('page')
try:
ct = paginate.page(page)
except PageNotAnInteger:
ct = paginate.page(1)
except EmptyPage:
ct = paginate.page(paginate.num_pages)
我该如何解决这个问题?
答案 0 :(得分:0)
如果我正确理解了您的问题和疑问,我认为您应该执行以下操作:
cit = City.objects.all().values_list('name', flat=True)
然后
.....filter(address__city__name__in=cit)
首先获取所有城市的名称。之后,将过滤从__exact
更改为__in
答案 1 :(得分:0)
在您的代码中,如果城市来自GET params是“请选择一个城市”,那么您需要一个包含数据库中所有城市的查询集。
if city == 'Please select a city':
cit = City.objects.all()
当您执行以下查询时:
.filter(address__city__name__exact=cit)
cit实际上是一个查询集,而Django ORM又转向子查询,从而产生了不需要的东西。
你可能需要有两个查询,一个过滤精确,一个过滤,但在这种情况下,甚至需要过滤器?