问题
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