Last time I asked how to filter without getting duplicates and I was advised to use distinct() and it helped, but now I wanted to add sorting by relevance using SearchRank and after that duplicates appeared in the queryset again, and distinct( ) dosent help.
my models:
class Book(models.Model):
...
genres = models.ManyToManyField(
Genre, related_name='book', blank=True)
...
class Genre(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
my query string
?genre=Supernatural&genre=Romance
and view
class BookList(ListView):
template_name='book/list.html'
context_object_name = 'list'
def get_queryset(self):
book=Book
genres = self.request.GET.getlist('genre')
search_vector = SearchVector('genres__name')
if genres:
search_query = SearchQuery(genres.pop())
for genre in genres:
search_query |= SearchQuery(genre)
book=book.objects.all().values('id','title__original_name','image').\
annotate(rank=SearchRank(search_vector,search_query)).\
filter(genres__name__in=genres).order_by('rank').distinct()
else:
book=book.objects.all().values('id','title__original_name','image')
return book
As i understand, i get duplicate for each match in SeqrchQuery and if my book, for example, match 4 times with SeqrchQuery, then i get 4 instance of it in my queryset.