[Fixed]-Simple Filter in django rest framework

1👍

DRF-extensions has a feature called Nested routes that allows you to append route logic to ViewSets (which is your case). It looks like what you want and the simplest.

0👍

You need to create filtered query set. here in this example i have filtered comments by author id

views.py

class CommentFilter(generics.ListAPIView):
    serializer_class = CommentSerializer

    def get_queryset(self):
        """
        This view should return a list of all the comments for
        particular author by author portion of the URL.
        """
        username = self.kwargs['author_id']
        return Comment.objects.filter(author__id=author_id)

urls.py

from django.conf.urls import url, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'comments', views.CommentViewSet)
router.register(r'comment_list/(?P<author_id>\d+)/?$', views.CommentFilter,base_name="comment_list")

Hope it works.

0👍

Nested URLs are unnecessarily difficult in DRF. As the issue that you linked hints, it’s simplest to just extract a query parameter:

class CommentViewSet(viewsets.ModelViewSet):
    serializer_class = ClubSerializer

    def get_queryset(self):
        queryset = Club.objects.all()
        author_id = self.request.query_params.get('author_id')

        if author_id is not None:
            queryset = queryset.filter(author_id=author_id)
        return queryset

You’d use this like your option 2 above:

api/comments?author_id=author_id

Leave a comment