0

点击搜索按钮后,我有这个网址:

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

但是现在,如果我同时查找名称和城市,它只会在名称之后给出结果搜索。例如第一个参数。第二个没有被采取。

最好的逻辑是什么?我也希望能够对搜索结果进行排序。你能给我一些提示吗?如何以干净的逻辑处理这种事情。

谢谢

4

1 回答 1

2

如果要过滤其中一个或两个参数或不过滤参数,则返回第一个,请尝试使用带有动态过滤器的查询集,例如

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)
于 2013-05-20T08:33:21.633 回答