0

I try to get related objects by get title of the current objects and and filter the common words between two titles, I could able to make something but it is not accurete

I get the title and split it using .split() and use Q to filter by first and second word but this not accurate

.What I want to do

I want get results by get the common words between the current object title and result title

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]))
Ahmed
  • 280
  • 1
  • 12
  • please provide sample input and output that you want to achieve – dchoruzy Jul 06 '21 at 17:25
  • For Examble I have current object with title `avangers team with spiderman` and want all the suggested objects title that contains `['avangers ', 'spiderman']` `common words` – Ahmed Jul 06 '21 at 17:32
  • 1
    There are many [string similarity](https://pypi.org/project/textdistance/) algorithms that could be useful in your case. – RJ Adriaansen Jul 06 '21 at 18:22
  • 1
    @Ahmed, for `avangers team with spiderman` do you also want objects with only `avangers` or with only `team` common word? – dani herrera Jul 06 '21 at 18:51
  • @daniherrera yes with avangers , My idea is to get for examble 2 most common words among books and show books based on this common words – Ahmed Jul 06 '21 at 21:58

1 Answers1

1

As per Gareth answer with Q constructor:

from django.db.models import Q

def get_queryset(self):
    book_pk = self.kwargs['pk']
    book = Video.objects.get(pk=book_pk)
    title = book.title # For ex, 'Harry Potter'
    title_list = title.split() # make a list ['Harry', 'Potter']

    q = Q()
    for each_title in title_list:
        q |= Q(title__icontains = each_title) # | or is used to either harry or potter

    
    return Book.objects.filter(q)

Above for loop query simplifies to:

Book.objects.filter(Q(title__icontains = 'Harry') | Q(title__icontains = 'Potter'))

Which means filter the Book objects if title contains 'Harry' or 'Potter' or 'ANY-OTHER-KEYWORDS'.

Siva Sankar
  • 1,672
  • 1
  • 9
  • 16