1

I am working on search functionality and I need to implement SearchHeadline to highlight searched words however I am struggling to do it in multiple fields.

What I'd like to do is to highlight not only words in the title field but also the short_description field. I found this question and tried to implement Concat however, in my case title and short_description are placed in 2 seperated html elements so I cannot just concatenate them and display as 1 headline because I need to display the whole title and the whole short_description and highlight matching words.

views.py

class SearchResultsList(LoginRequiredMixin, ListView, CategoryMixin):
    model = QA
    context_object_name = "query_list"
    template_name = "search/SearchView.html"
    
    def get_queryset(self):
        query = self.request.GET.get("q")
        search_vector = SearchVector("title", weight="A") + SearchVector("short_description", weight="B")
        search_query = SearchQuery(query)
        search_headline = SearchHeadline('title', search_query, start_sel='<span class="text-decoration-underline sidebar-color">',stop_sel='</span>') # how to implement SearchHeadline to short_description?
        return QA.objects.annotate(
            search=search_vector,
            rank=SearchRank(search_vector, search_query)
        ).annotate(headline=search_headline).filter(rank__gte=0.3).order_by("-rank")

        #The code below is working but it concatenates the title with the short description and I need to separate these fields. Moreover, it shows only a preview, not the whole title and short description value
        # return QA.objects.annotate(search_vectors=SearchVector('title', 'short_description'), ).annotate(headline=SearchHeadline(Concat(F('title'), Value(' '), F('short_description')),SearchQuery(query),start_sel='<strong>', stop_sel='</strong>')).filter(search_vectors=SearchQuery(query))

SearchView.html

{% for query in query_list %}
    <div class="col-12">
        <a href="{{ query.get_absolute_url }}"><h2>{{query.headline | safe}}</h2></a>
        <p>{{query.short_description |safe}}</p> # how to implement SearchHeadline to short_description so it displayed whole text and highlights matching words as in the title field?
    </div>
{% empty %}
    <div>No results</div>
{% endfor %}
Adrian
  • 725
  • 4
  • 18

0 Answers0