django haysteck FacetedSearchView返回空结果?

时间:2018-03-11 12:45:52

标签: django django-haystack

我使用Django haystack FacetedSearchView my views.py

from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView
class FacetedSearchView(BaseFacetedSearchView):
    template_name = 'test.html'
    facet_fields = ['source']  

urls.py

url(r'^search', FacetedSearchView.as_view(), name='haystack_search')

并在test.html中我打印了facet。当我发出如下请求时:

127.0.0.1:8000:/search

factes上下文对象的内容为空dict。但我认为它应该返回facets_fields中我指定的所有方面,并且当我将q参数附加到请求的查询字符串(具有任何值)时,它返回结果但文档为零。是否需要提供q参数?和哪个价值?

1 个答案:

答案 0 :(得分:0)

解决了需要覆盖FacetedSearchForm的搜索方法的问题,因为原始实现假设查询“q'但只需要facet_fields才能实现分面。

from haystack.forms import FacetedSearchForm as BaseFacetedSearchForm
from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView
class FacetedSearchForm(BaseFacetedSearchForm):
    def __init__(self, *args, **kwargs):
        self.selected_facets = kwargs.pop("selected_facets", [])
        super(FacetedSearchForm, self).__init__(*args, **kwargs)

    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        sqs = self.searchqueryset
        # 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)))

        if self.load_all:
            sqs = sqs.load_all()

        return sqs

class FacetedSearchView(BaseFacetedSearchView):
    template_name = 'facets.html'
    facet_fields = []
    form_class = FacetedSearchForm