views.py 2.0 KB

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