Drill down the haystack search results with facets but not changing the facet results

血红的双手。 提交于 2019-12-04 16:46:19

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.

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.

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