Following Danielle Madeley's advice, I also created a proxy server for finding results that works well with the latest version of django-elasticsearch-dsl==0.4.4
.
from django.utils.functional import LazyObject class SearchResults(LazyObject): def __init__(self, search_object): self._wrapped = search_object def __len__(self): return self._wrapped.count() def __getitem__(self, index): search_results = self._wrapped[index] if isinstance(index, slice): search_results = list(search_results) return search_results
Then you can use it in your search type as follows:
paginate_by = 20 search = MyModelDocument.search() # ... do some filtering ... search_results = SearchResults(search) paginator = Paginator(search_results, paginate_by) page_number = request.GET.get("page") try: page = paginator.page(page_number) except PageNotAnInteger: # If page parameter is not an integer, show first page. page = paginator.page(1) except EmptyPage: # If page parameter is out of range, show last existing page. page = paginator.page(paginator.num_pages)
Django LazyObject proxies all attributes and methods from the object assigned to the _wrapped attribute. I override several methods that are required in paginator Django, but do not work out of the box with Search () instances.
source share