首页 文章

Django / Haystack - 拥有搜索功能列表视图的最佳选择

提问于
浏览
1

我有一个餐厅模型的应用程序 . 我想了解将显示餐馆对象列表的视图组合在一起的最佳方法是什么,但上面还有一个搜索表单,用户可以输入参数来过滤显示的结果 . 如果未输入参数,则应显示所有餐馆 . 我已经在使用haystack并有一个搜索表单,但目前它是在一个独立的search.html模板上 . 我在一个单独的模板上也有一个ListView,我想我正在寻找一个结合这些的最终结果 .

我做了一些在线阅读,目前还不清楚最好的方法是:

  • 使用Django的listview进行一些查询集过滤

  • 将haystack SearchView与基于django类的视图相结合?

  • 这是我迄今为止最好的选择 - 从Haystack创建一个自定义版本的SearchView

理想情况下,搜索功能最终将包括允许自动填充用户输入,以及在用户输入时动态过滤结果 .

有什么最好的方法来解决这个问题以及那里的任何例子吗?

1 回答

  • 2

    可能有一些软件包可以自动为您提供所有内容,显示查询集列表并允许简单添加搜索栏等(如管理站点) . 但我认为你仍然是网络开发的初学者,所以我强烈建议你删除列表视图,删除haystack,删除所有内容,然后自己完成所有操作 .

    看,他们不是坏方法或任何东西,但他们就像快捷方式 . 并且快捷方式只有在缩短原始方式时才有用,在您的情况下,这种方式并不长 .

    举个例子,这是一个显示项目列表的简单方法:

    views.py

    def restaraunt_list(request):
        restaraunts = Restaraunt.objects.all().order_by('name')[:100] # Just for example purposes. You can order them how you'd like, and you probably want to add pagination instead of limiting the view number arbitrarily
    
        context = {'restaraunts': restaraunts}
        return render_to_response('index.html', context)
    

    index.html的:

    <ul>
    {% for rest in restaraunts %}
        <li>{{ rest }}</li>
    {% endfor %}
    </ul>
    

    而已 . 现在它将其显示在列表中 . 现在要添加搜索过滤器,您需要做的就是:

    index.html(在任何你想要的地方添加)

    <form>
        <input type='text' name='q' id='q'></input>
        <input type='submit' value='search!'></input>
    </form>
    

    当用户从'q'发送数据时,它通过GET发送,然后在服务器端添加:

    def restaraunt_list(request):
        restaraunts = Restaraunt.objects.all()
    
        # filter results!
        if request.method == 'GET':
            q = request.GET['q']
            if q != '':
                restaraunts = restaraunts.filter(name__contains=q)
    
        # ordering is the last thing you do
        restaraunts = restaraunts.order_by('name')[:100] 
    
        context = {'restaraunts': restaraunts}
        return render_to_response('index.html', context)
    

    现在,这将起作用,但是根据你所写的内容,我理解你希望在按下按键时搜索才能生效 . 为此,你_1675822_我不会在这里钻研) . 至于自动完成,你应该看看jQuery UI .

    但是,就像我说的那样,在开始使用所有这些东西之前,我建议你先学习基础知识 . 通过django tutorial(如果你没有't already), and use the amazingly detailed django-docs every step of the way. When some specific things won'工作而且你被困住了,来到Stackoverflow,有人肯定会帮助你 . 祝你好运!

相关问题