点击搜索按钮后我有这个网址:
127.0.0.1:8000/results/?name=blab&city=bla&km=12
我的观点:
def search(request):
name = request.GET.get('name')
city = request.GET.get('city')
km = request.GET.get('km')
if name!="" and name != None:
locations = Location.objects.filter(name__istartswith=name)
return render_to_response("result-page.html",{'locations':locations},context_instance=RequestContext(request))
if city!="" and city != None:
locations = Location.objects.filter(city__istartswith=city)
return render_to_response("result-page.html",{'locations':locations},context_instance=RequestContext(request))
但是现在,如果我同时寻找名称和城市名称,它会在名称后给出结果搜索。例如第一个参数。第二个没有被采取。
这是什么最好的逻辑?我也希望能够对搜索结果进行排序。能不能给我一些提示,告诉我如何用干净的逻辑来做这类事情。
感谢
答案 0 :(得分:2)
如果您想要过滤其中一个或两个参数,或者没有参数尝试使用带有动态过滤器的一个QuerySet,则返回第一个if
之类的东西search_kwargs = {}
if request.GET.get('name'):
search_kwargs['name__istartswith'] = request.GET.get('name')
if request.GET.get('city'):
search_kwargs['city__istartswith'] = request.GET.get('city')
locations = Location.objects.filter(**search_kwargs)
return render_to_response("result-page.html",{'locations':locations},context_instance=RequestContext(request))
甚至是
之类的东西filter_fields = ['city','name']
for f in filter_fields:
if f in request.GET:
search_kwargs['%s__istartswith' % f] = request.GET.get(f)