【问题标题】:GET url in search and sort logic在搜索和排序逻辑中获取 url
【发布时间】:2013-05-20 08:28:26
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

    标签: django url search


    【解决方案1】:

    如果您想过滤其中一个或两个参数或不过滤参数,则您将返回第一个,请尝试使用带有动态过滤器的 QuerySet,例如像

    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)
    

    【讨论】:

    • 太棒了! ** 是做什么的?
    • 是的,您可以添加任意数量的过滤器(任何类型的 - icontains、equals 等),只要您想 search_kwargs,如果这就是您的意思?
    • 但我有这个查询:Location.objects.filter(locations_rate__rate=int_bew).distinct('id') 我怎么能把它放到 dict 中?
    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    相关资源
    最近更新 更多