Django-filters does not work with the Viewset

放肆的年华 提交于 2019-12-02 03:12:24

Okay, So finally found the solution from DRF Docs. The issue was that in case of normal ViewSet you have to override the method filter_queryset() and return the appropriate queryset accordingly. Then use the queryset under filter_queryset as mentioned by Aman -

serializer = PostListSerializer(self.filter_queryset(self.get_queryset()), many=True, context={"request": request})

Below is the code for reference for those who are still facing issues -

filter_queryset -

def filter_queryset(self, queryset):
    filter_backends = (DjangoFilterBackend, )

    # Other condition for different filter backend goes here

    for backend in list(filter_backends):
        queryset = backend().filter_queryset(self.request, queryset, view=self)
    return queryset

You have overwrite the list method, so it's not working to work call the filter_queryet method.

def list(self, request, *args, **kwargs):
    """
     Method for Post listing. It can be accessed by anyone.
     """

    serializer = PostListSerializer(self.filter_queryset(self.get_queryset()), many=True, context= . 
     {"request": request})

    return Response(serializer.data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!