Sort queryset Django by priority

Asked

Viewed 154 times

2

I am creating a search system on my platform. I do a search for the title of the content, description and tags within it. Follow the code:

questions = Question.objects.filter(reduce(lambda x, y: x | y, [(Q(name__icontains=word) | Q(description__icontains=word) | Q(tags__name__icontains=word)) for word in words]))

That way, I can break the words of the text and do a really cool search. The problem is, I’d like to sort by a priority that I create, in case, wanted to do in the following order:

  1. Exact result
  2. Result starting with word/phrase
  3. Result ending with word/phrase
  4. Result containing in word/phrase

This way I will display first the result which is exactly what the user looks for, then results that start with what he searches for, finish and which contains.

But with my code, I can’t see a way to do that sql pure using case when.

1 answer

-1

I found a solution but I don’t know if it’s the best one. To tell you the truth shouldn’t be because I have to make 2 querys to bring 1 list.

I create 2 querysets, being the first for the exact match and the second for the possible matchs (as I am doing in the example I asked the question). Follows the code:

from functools import reduce    

words = text.split()
q1 = Question.objects.filter(name__istartswith=text)[:1]
if q1.count() > 0:
    q1 = [q1[0]]
else:
    q1 = []

q2 = Question.objects.filter(reduce(lambda x, y: x | y, [Q(name__icontains=word) for word in words]))[:4]
if q1:
    q2.exclude(id=q1[0].id)

if q2.count() > 0:
    q2 = [q for q in q2]
else:
    q2 = []

questions = list(q1) + list(q2)

In the end he returns me the 5 results being the 1 the perfect match.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.