Sorting filtered results based on word occurrence using Django Model Filter

Viewed 56

Platform: Django 1.1, Python 3.6 on a Linux server, backend is MySQL.

I'm after a fairly common functionality but I need guidance to where/how to begin this:

I have a model object called Article. I'm trying to implement a search function that retrieves articles based on searched terms, and then sort based on occurrences of words in the searched term.

In Article, I have the following fields that I'd like to sort or 'prioritise' based on:

- name, a text field
- keywords, also a text field but would contain comma-separated words
- article_text, a text area field that will contain the article itself

I want to basically sort the most relevant article to the least relevant, based on the searched terms input against name, keywords, and occurrences of words in article_text.

In my views.py I have this function that triggers on request.POST:

    form_data['search_term'] = request.POST.get('search_term')
    #removing question mark from term
    search_term = search_term.replace("?","")

    #Converting terms to a list of words, then converting all words to lowercase
    search_terms_list = search_term.split(' ')
    search_terms_list = [x.lower() for x in search_terms_list]
    #Fetching results
    results = Article.objects.filter(reduce(lambda x, y: x | y, 
       [Q(name__icontains=word) | Q(keywords__icontains=word) | Q(article_text__icontains=word) for 
       word in search_terms_list]))

I am retrieving the right results but sorted based on article PK, which makes sense. Is there a way I can achieve the aforementioned without having to go to a 3rd party plugin?

1 Answers

I would suggest you to create a table in which you save the articles and the number of times a word is retrieved inside each article, then you order that table by the number of times the searched term is retrieved, in descendand order, and pass it to your template.

Related