How to filter sentences from an list of words in array in Django

Viewed 227

I create like books site, I want to show related book by the title of this book, by at least 2 words to be accurate in suggest books, Firstly I split the title of the current book into an array of words like ['good', 'book', 'by', 'mickle'] and filter the books using title__icontains but it shows an empty list

My question is how I can filter sentences from a list of words in an array? and if there is a better way to get the related objects by title at least two similar word from the title

My Book title

   class Book(models.Model):
       author = models.models.ForeignKey(Account, on_delete=models.CASCADE)
       title = models.CharField(max_length=90, null=True, blank=True)

My function to get the related books by title.

class BookRelatedObj(ListAPIView):
serializer_class = BookRelatedSerializer
lookup_field = 'title'
def get_queryset(self):
    book_pk = self.kwargs['pk']
    book = Video.objects.get(pk=book_pk)
    lst = book.title
    split = lst.split()

    print(split)
    return Book.objects.filter(title__icontains=[split])
2 Answers

I solved this problem by using Q

def get_queryset(self):
    book_pk = self.kwargs['pk']
    book = Video.objects.get(pk=book_pk)
    lst = book.title
    split = lst.split()

    return Book.objects.filter(Q(title__icontains=split[0]) & Q(title__icontains=split[1]))

this get the first and secon word of title and try to get a books with titles that contains this words

You don't need a split list for accuracy Django is smart enough to get the required accuracy

But if you need to implement your solution you can edit your query to

Book.objects.filter(title__icontains__in=[split]

We have put _in the query because you search items in list not search by word

Related