正确获取Django搜索查询

时间:2018-06-20 16:43:49

标签: django search view

自几天以来,我目前正面临问题。我只是想在我的Django应用中实现搜索视图。但是,当我尝试在我的应用程序上搜索内容时,出现以下错误:

init ()接受1个位置参数,但给出2个位置参数__init __()接受

最后,我希望我的查询是类别和搜索词的组合。以便用户可以过滤特定类别(就像Amazon.com搜索字段一样),例如:ubuntu:~$ node -v v6.10.3

base.html

table {  max-width: 100%; }
table > thead > tr > th { max-width: 100px;  }
table > thead > tr > th:first-child {  width: auto; max-width: 100%;  }

categorysearch_form是一个下拉选择器,可从数据库中获取其ID。

views.py

http://127.0.0.1:8000/search/?category=1&q=hallo

urls.py

...
   <div class="globalsearch">
            <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8">
                <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }}
                <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ...">
                <button class="searchbutton" type="submit">
                    <i class="fa fa-search"></i>
                </button>
            </form>
        </div>
    </div>

...

Search.html 结果在此处显示:

...
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.views.generic import ListView


class globalsearch(ListView):
"""
Display a Post List page filtered by the search query.
"""
model = Post
paginate_by = 10

def get_queryset(self):
    qs = Post.objects.published()

    keywords = self.request.GET.get('q')
    if keywords:
        query = SearchQuery(keywords)
        title_vector = SearchVector('title', weight='A')
        content_vector = SearchVector('content', weight='B')
        tag_vector = SearchVector('tag', weight='C')
        vectors = title_vector + content_vector + tag_vector
        qs = qs.annotate(search=vectors).filter(search=query)
        qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank')

    return qs

...

项目:https://github.com/rsmvdl/quickblog

1 个答案:

答案 0 :(得分:0)

由于globalsearch是基于类的视图,因此它应该在您的网址中为globalsearch.as_view()

url(r'^search/$', views.globalsearch.as_view(), name='search'),