Advanced search in django rest framework

47 Views Asked by At

I have a database containing lots of posts with a number of fields(title, content, tags). I want to build a search system to look for posts. It seemed really easy first but it turns out it is not. For instance, when I type 'how to' I want my system show posts containing at least one of the word('how' or 'to' or 'how to' is the best scenario) but the problem is when I type 'how to' my system searches for only posts containing 'how to' not 'how' or 'to'. Please help me to build the system.

class PostsSearch(APIView):
    def get(self, request, format=None):
        search = request.GET.get('search')
        query = SearchQuery(search)
        vector = SearchVector('title') + SearchVector('tags__name')
        posts = Post.objects.prefetch_related('tags').annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.0001).order_by('-rank')
        serializer = PostsSerializer(posts, many=True)
        return Response(serializer.data)

I tried the code I provided above but it does not work at all

1

There are 1 best solutions below

0
P. Naoum On

For the scenario mentioned of "how to" you can simply reduce the search to the list of words, for example:

from functools import reduce
import operator
from django.db.models import Q

q = "how to"
results = Post.objects.filter(reduce(operator.or_, (Q(content__icontains=k) for k in q.strip().split())))