Saturday, January 21, 2017
Django Haystack - how to limit number of search results
Hello friends,
Recently I needed to limit number of search results in haystack and that was a bit of a challenge. So I decided to share it with you here.
I knew how to limit search results using old style views (haystack.views.SearchView):
But at this time I needed to switch to new-style views (haystack.generic_views.SearchView), which use standard Django views. Obviously previous hack to limit results didn't work and I started brainstorming it by trying to override different methods, reading docs, etc. And finally I got this solution:
The reason I'm using paginate_queryset is because it's the last method called to fetch the results from the db and thus we can do a slice. But if you have a better idea how to limit results, feel free to let me know.
Recently I needed to limit number of search results in haystack and that was a bit of a challenge. So I decided to share it with you here.
I knew how to limit search results using old style views (haystack.views.SearchView):
from haystack.views import SearchView class MySearchView(SearchView): #limit maximum results def get_results(self): return self.form.search()[:100]
But at this time I needed to switch to new-style views (haystack.generic_views.SearchView), which use standard Django views. Obviously previous hack to limit results didn't work and I started brainstorming it by trying to override different methods, reading docs, etc. And finally I got this solution:
from haystack.generic_views import SearchView class MySearchView(SearchView): template_name='search/search.html' #.... def paginate_queryset(self, queryset, page_size): return super(MySearchView, self).paginate_queryset(queryset[:100], page_size)
The reason I'm using paginate_queryset is because it's the last method called to fetch the results from the db and thus we can do a slice. But if you have a better idea how to limit results, feel free to let me know.
Subscribe to:
Post Comments (Atom)
Do you need to map URL to the new view or leave it as url(r'^search/', include('haystack.urls')),
ReplyDeleteThanks