Remove unnecessary extra query during search

Just pass the original queryset, which helps ordering and performance
This commit is contained in:
Jake Howard 2022-08-28 12:56:26 +01:00
parent 4ca2a97b2a
commit edbedcd0fa
Signed by: jake
GPG Key ID: 57AFB45680EDD477

View File

@ -7,7 +7,6 @@ from django.utils.functional import cached_property
from django.views.decorators.http import require_GET from django.views.decorators.http import require_GET
from wagtail.contrib.routable_page.models import RoutablePageMixin, route from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.models import Page from wagtail.models import Page
from wagtail.query import PageQuerySet
from wagtail.search.utils import parse_query_string from wagtail.search.utils import parse_query_string
from website.common.models import BaseContentPage from website.common.models import BaseContentPage
@ -63,7 +62,11 @@ class SearchPage(RoutablePageMixin, BaseContentPage):
} }
filters, query = parse_query_string(search_query) filters, query = parse_query_string(search_query)
pages = Page.objects.live().not_type(self.__class__, HomePage).search(query) pages = (
Page.objects.live()
.not_type(self.__class__, HomePage)
.search(query, order_by_relevance=True)
)
paginator = Paginator(pages, self.PAGE_SIZE) paginator = Paginator(pages, self.PAGE_SIZE)
context["paginator"] = paginator context["paginator"] = paginator
@ -72,12 +75,11 @@ class SearchPage(RoutablePageMixin, BaseContentPage):
results = paginator.page(page_num) results = paginator.page(page_num)
# HACK: Search results aren't a queryset, so we can't call `.specific` on it. This forces it to one as efficiently as possible # HACK: Search results aren't a queryset, so we can't call `.specific` on it. This forces it to one as efficiently as possible
if not isinstance(results.object_list, PageQuerySet): results.object_list = (
results.object_list = Page.objects.filter( results.object_list.get_queryset()
id__in=list( .specific()
results.object_list.get_queryset().values_list("id", flat=True) .select_related("hero_image", "hero_unsplash_photo")
) )
).specific()
except EmptyPage: except EmptyPage:
results = [] results = []