djangowagtailwagtail-search

Searching Pages and custom models at the same time in Wagtail


I made a blunder - implemented some models in our application as plain Django models (but Indexable) instead of Page models.

Now the client would like to see a unified search results page (so a faceted search is not adequate)... so I am completely stuck.

We are using the PostgreSQL backend. The s.search() function requires a model or queryset; and you cannot combine PostgresSearchResults query sets. If I convert the 2 result sets to list and combine them I lose the relevancy of the results.

Any ideas?


Solution

  • For the purposes of rendering non-homogenuous search results, you can use:

    from itertools import chain

    And let's say you've searched pages, documents, images, and also have some other results - you can do this (including pagination since you'll need that too):

    page_results = SOME PAGE RESULTS
    doc_results = docs_to_search.search(search_query, order_by_relevance=False)
    img_results = images_to_search.search(search_query, order_by_relevance=False)
    other_search_results = SOME RESULTS FROM SEARCHING MODELS
    
    all_results = list(chain(other_search_results, page_results, img_results, doc_results))
    
    # Pagination
    paginator = Paginator(all_results, items_per_page, orphans=num_orphans)
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)
    except EmptyPage:
        results = paginator.page(paginator.num_pages)
    

    and then return your results from your view and render in the template with {% for result in results %}