2013-05-20 52 views
0

我有這個網址,你點擊搜索按鈕後:GET URL

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

但現在,如果我找這兩個名稱和城市,它給出了名字後的搜索結果。例如第一個參數。第二個沒有被採取。

這是什麼最好的邏輯?我也想要對搜索結果進行排序。你能否給我一些提示,告訴我如何在乾淨的邏輯中處理這種事情。

感謝

回答

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

太棒了! '''''做什麼? – doniyor

+0

請參閱 - http://stackoverflow.com/a/2921893/188955,傳遞關鍵字參數 – JamesO

+0

我還可以將不同的過濾器設置爲字典,對嗎? – doniyor