views.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from django.conf import settings
  2. from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
  3. from django.shortcuts import render
  4. from wagtail.models import Page
  5. from wagtail.search.models import Query
  6. from bakerydemo.blog.models import BlogPage
  7. from bakerydemo.breads.models import BreadPage
  8. from bakerydemo.locations.models import LocationPage
  9. def search(request):
  10. # Search
  11. search_query = request.GET.get("q", None)
  12. if search_query:
  13. if "elasticsearch" in settings.WAGTAILSEARCH_BACKENDS["default"]["BACKEND"]:
  14. # In production, use ElasticSearch and a simplified search query, per
  15. # https://docs.wagtail.org/en/stable/topics/search/backends.html
  16. # like this:
  17. search_results = Page.objects.live().search(search_query)
  18. else:
  19. # If we aren't using ElasticSearch for the demo, fall back to native db search.
  20. # But native DB search can't search specific fields in our models on a `Page` query.
  21. # So for demo purposes ONLY, we hard-code in the model names we want to search.
  22. blog_results = BlogPage.objects.live().search(search_query)
  23. blog_page_ids = [p.page_ptr.id for p in blog_results]
  24. bread_results = BreadPage.objects.live().search(search_query)
  25. bread_page_ids = [p.page_ptr.id for p in bread_results]
  26. location_results = LocationPage.objects.live().search(search_query)
  27. location_result_ids = [p.page_ptr.id for p in location_results]
  28. page_ids = blog_page_ids + bread_page_ids + location_result_ids
  29. search_results = Page.objects.live().filter(id__in=page_ids)
  30. query = Query.get(search_query)
  31. # Record hit
  32. query.add_hit()
  33. else:
  34. search_results = Page.objects.none()
  35. # Pagination
  36. page = request.GET.get("page", 1)
  37. paginator = Paginator(search_results, 10)
  38. try:
  39. search_results = paginator.page(page)
  40. except PageNotAnInteger:
  41. search_results = paginator.page(1)
  42. except EmptyPage:
  43. search_results = paginator.page(paginator.num_pages)
  44. return render(
  45. request,
  46. "search/search_results.html",
  47. {
  48. "search_query": search_query,
  49. "search_results": search_results,
  50. },
  51. )