Home > OS >  Filtering by query params in many to many relationship using drf
Filtering by query params in many to many relationship using drf

Time:10-16

I have two models:

class Book(models.Model):
    id = models.CharField(verbose_name="unique id", primary_key=True, max_length=256)
    title = models.CharField(max_length=256)
    published_date = models.CharField(max_length=128, blank=True, null=True)
    average_rating = models.IntegerField(blank=True, null=True, default=None)
    ratings_count = models.IntegerField(blank=True, null=True, default=None)
    thumbnail = models.URLField(verbose_name="thumbnail url", null=True, blank=True, default=None)

class Author(models.Model):
    name = models.CharField(null=True, blank=True, max_length=256)
    books = models.ManyToManyField(Book, related_name='authors')

What i want to achieve is that i want to filter api queries by using query params like this:

127.0.0.1/books?author='something'

So my param is something in that case.

I want to filter by names of authors and check if there are books that have relationship with this authors. Also it is important that there could be more than just one param at the time like this:

?author='something1'&author='something2'

I have no idea how to achieve this. I'm trying with default filtering using get_queryset function in generic classes of DRF, but have no idea still.

CodePudding user response:

This should be easily done with DjangoFilterBackend.

You can try and follow the steps here

under Generic Filtering.

If that doesn't work - you can try a third-party package like django-filters :) Let me know how it goes :)

CodePudding user response:

The right way is to use django-filter: https://django-filter.readthedocs.io/en/stable/guide/install.html

Like this:

class BookFilterSet(filters.FilterSet):
    
    class Meta:
        model = Book
        fields = ['authors']

class BookViewSet(ModelViewSet):
    serializer_class = BookSerializer
    queryset = Book.objects.all()
    filter_backends = [filters.DjangoFilterBackend]
    filterset_class = BookFilterSet
  • Related