django haysteck FacetedSearchView returning empty results?

喜你入骨 提交于 2020-01-06 05:36:06

问题


I'm using Django haystack FacetedSearchView my views.py:

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

and in urls.py:

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

and in test.html I'm printing the facets. when I issue request as follow:

127.0.0.1:8000:/search

the content of the factes context object is empty dict. but I think it should return all the I specified facets in facets_fields, and when I append q parameter to the request's querystring (with any value) it returns result but with zero document. is it neccessary to provide the q parameter? and with which value?


回答1:


to solve the issue on need to override the search method of FacetedSearchForm, because the original implementation assumes a query 'q' but faceting needs only facet_fields to work.

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


来源:https://stackoverflow.com/questions/49220132/django-haysteck-facetedsearchview-returning-empty-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!