django haystack如果找到与属性完全匹配的分面搜索重定向

时间:2015-04-06 19:32:33

标签: django django-haystack

如果商店模型的name属性完全匹配,我需要将用户重定向到详细信息页面。如果是任何其他财产,它应该只是搜索结果页面而不管是否直接匹配。

我目前正在使用覆盖buid_page,FacetedSearchCustomViewcreate_reponse方法的extra_content。但我无法找到查询查询结果的方法,因为query._results受到保护。

有关如何执行此操作的任何建议。

由于

已更新

FacetedSearchCustomView.py

class FacetedSearchCustomView(FacetedSearchView):
"""
Overrides various default methods to allow for additional context, smoother UX for faceting
"""

def build_page(self):
    """
    Paginates the results appropriately.

    Overriden to redirect to page 1 if a page_no is not found
    """
    try:
        page_no = int(self.request.GET.get('page', 1))
    except (TypeError, ValueError):
        raise Http404("Not a valid number for page.")

    if page_no < 1:
        raise Http404("Pages should be 1 or greater.")

    paginator = NamedPaginator(self.results, on="brand", per_page=self.results_per_page)
    # import pdb; pdb.set_trace()
    try:
        page = paginator.page(page_no)
    except InvalidPage:
        # Redirect to page 1 of the
        path = self.request.path
        qs = self.request.GET.copy()
        qs['page'] = 1
        url = '%s?%s' % (path, qs.urlencode())
        return redirect(url)

    return paginator, page

def clean_filters(self):
    """Returns a list of tuples (filter, value) of applied facets"""
    filters = []
    # get distinct facets
    facets = list(set(self.form.selected_facets))
    for facet in facets:
        if ":" not in facet:
            continue
        field, value = facet.split(":", 1)
        field = field.replace('_', ' ').replace('exact', '').title()
        filters.append((field, value))
    return filters

def create_response(self):
    """
    Generates the actual HttpResponse to send back to the user.

    Overriding to allow the redirect to pass through from overriden build_page
    """
    try:
        (paginator, page) = self.build_page()
    except ValueError:
        return self.build_page()

    context = {
        'query': self.query,
        'form': self.form,
        'page': page,
        'paginator': paginator,
        'suggestion': None,
    }

    if self.results and hasattr(self.results, 'query') and self.results.query.backend.include_spelling:
        context['suggestion'] = self.form.get_suggestion()

    context.update(self.extra_context())
    return render_to_response(self.template, context, context_instance=self.context_class(self.request))

def extra_context(self):
    extra = super(FacetedSearchCustomView, self).extra_context()
    extra['filters'] = self.clean_filters()
    if not self.results:
        extra['facets'] = self.form.search().facet_counts()
    else:
        extra['facets'] = self.results.facet_counts()

    model_type = self.request.path.split('/')[1].rstrip('s')
    extra['model_type'] = None if model_type == "search" else model_type

    # if model_type in ['package', 'project']:
    # extra['facets'] = self.clean_facets(extra['facets'])
    #     extra['model_create'] = '%s_create' % model_type
    return extra

CustomSearchForm.py

class CustomSearchForm(FacetedSearchForm):

def search(self):
    sqs = super(CustomSearchForm, self).search()

    # We need to process each facet to ensure that the field name and the
    # value are quoted correctly and separately:
    for facet in self.selected_facets:
        if ":" not in facet:
            continue

        field, value = facet.split(":", 1)

        if value:
            sqs = sqs.narrow(u'%s:"%s"' % (field, sqs.query.clean(value)))

    return sqs

1 个答案:

答案 0 :(得分:0)

我过去通过查看SearchQuerySet.best_match然后比较名称来实现类似的功能。

http://django-haystack.readthedocs.org/en/latest/searchqueryset_api.html#SearchQuerySet.best_match