[Fixed]-DRF canned filter – best practice?

1👍

You can use DjangoFilterBackend. For detailed information, see the documentation.
After installation django-filter lib don’t forget to add DjangoFilterBackend in the settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
     )
}

and then use it in the view:

class TaskListCreateView(ListCreateAPIView):
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('status', )
    serializer_class = TaskSerializer

Alternative way to filter objects is use Filtering against query parameters. For this just to override get_queryset method:

class TaskListCreateView(ListCreateAPIView):
    def get_queryset(self):
        queryset = Task.objects.all()
        status = self.request.query_params.get('status', None)
        if status:
            queryset = queryset.filter(status=status)
        return queryset
👤M.Void

Leave a comment