I have the following 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)
I want to filter list of books with selected genres.
Fo example i may have query string something like this
?genre=Supernatural&genre=Romance
and in i have the following view
class BookList(ListView):
model = Book
template_name='book/list.html'
context_object_name = 'list'
def get_queryset(self):
book=Book
query = self.request.GET.getlist('genre')
if query:
book=book.objects.filter(Q(genres__name__icontains=query))
else:
book=book.objects.all()
return manga
but it doesn’t work and i get an empty list no matter what i choose. I tried replacing ‘icontains’ with ‘in’ but in this case I get duplicate results if the book contains more than 1 match
So I need a way to properly filter my model with zero or more matches