Home > Blockchain >  Multiple filters in django
Multiple filters in django

Time:06-05

I want to filter movies, that fit only to selected genres, for example:

def get_queryset(self):
    queryset = Movie.objects.all()
    if 'genres' in self.request.GET:
        queryset = queryset.filter(genre__in=self.request.GET.getlist('genres'))
    return queryset

This filter shows movies that fit into at least one to filter, but I want to show movies that are fit all of the selected genress like 'comedy, horror, fantasy' and all of the selected genres must be in the movie genres How cat I do this?

Models:

class Genre(models.Model):
    title = models.CharField('Title', max_length=100)
    description = models.TextField('Description')
    slug = models.SlugField(max_length=100, unique=True)

class Movie(models.Model):
    title = models.CharField('Title', max_length=100)
    tagline = models.CharField('Tagline', max_length=200, default='')
    description = models.TextField('Description')
    poster = models.ImageField('Poster', upload_to='movies/')
    country = models.CharField('Country', max_length=50)
    actors = models.ManyToManyField(
        Actor, verbose_name='actors', related_name='film_actor'
    )
    genres = models.ManyToManyField(
        Genre, verbose_name='genres', related_name='genres'
    )
    category = models.ForeignKey(
        Category,
        verbose_name='category',
        related_name='category',
        on_delete=models.SET_NULL,
        null=True
    )
    slug = models.SlugField(max_length=100, unique=True)

CodePudding user response:

maybe you're looking for this?

genre = ['horror', 'comedy'] (dummy list of genre)
queryset = queryset.objects.filter(genre__in=genre)

CodePudding user response:

If you're looking for a quick fix i believe this has already been answered quite well here: Django filter queryset __in for *every* item in list

In short, if you have a small set of genres (up to around 5) then you may add .filter() for each genre:

Movie.objects.filter(genre='genre1').filter(genre='genre2')....

Reference: https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

  • Related