Drill down the haystack search results with facets but not changing the facet results
I have search results showing with facet options for drilling dow开发者_Python百科n the data. When a facet is selected it then changes the facet results. So if I am originally showing "places (10)", "images (5)", "people (3)", and "All (18)" as faceting options and I click on images I would still like to see all the others too even though the search results changed. Is there a good way to do this?
I just did this and it's actually quite achievable without rerunning the original search query. you just need to use session to store the original facets.
Here's my actual working code:
from haystack.views import FacetedSearchView
class StickyFacetedSearchView (FacetedSearchView):
def top_level_facets(self):
"""
When selecting a facet to drill down the results,
we need to keep the top level facet counts
"""
stored_query = self.request.session.get('query', None)
if stored_query != self.query:
self.request.session['query'] = self.query
self.request.session['facet_counts'] = self.results.facet_counts()
return self.request.session['facet_counts'] # Fail loudly
def extra_context(self):
""" add base_facets to extra_context"""
extra = super(StickyFacetedSearchView, self).extra_context()
extra['base_facets'] = self.top_level_facets()
return extra
Stick the above view in an app called 'mysearch' or similar, then use mysearch.StickyFacetedSearchView in urls.py instead of FacetedSearchView.
To access them use base_facets in the template, rather than facets.
It works perfectly.
I've run into problems with this too. The only answer we could find was to re-run the query each time without the drill-down to get the top-level facet results.
精彩评论