My Django application has the following models:
class Book(models.Model): name = models.CharField(max_length=100) keywords = models.ManyToManyField('Keyword') class Keyword(models.Model) name = models.CharField(max_length=100)
I have the following saved keywords:
science-fiction fiction history science astronomy
On my site, a user can filter books by keyword by visiting /keyword-slug/ . The keyword_slug variable is passed to a function in my views that filters Books by keywords as follows:
def get_books_by_keyword(keyword_slug): books = Book.objects.all() keywords = keyword_slug.split('-') for k in keywords: books = books.filter(keywords__name__icontains=k)
This works for the most part, however whenever I filter a keyword that contains a string that appears more than once in the keyword table (e.g. science-fiction and fiction ), I get the same book more than once in the resulting QuerySet.
I know that I can add distinct to only return unique books, but I wonder why I get duplicates for a start and really want to understand why this works the way it does. Since I only call filter() on successfully filtered QuerySets, how is a duplicate book added to the results?
source share