2013-05-20 10 views
0

당신이 검색 버튼을 누르면 후 나는이 URL을 가지고 :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

dict에 다른 필터를 설정할 수도 있습니다. 맞습니까? – doniyor