[Fixed]-Django swagger- How to disable DjangoFilterBackend query filters from delete, put methods?

9πŸ‘

βœ…

If you don’t want to Add Schema Manually(Every time) then Here is the solution:
auto_schema.py

from rest_framework.schemas import AutoSchema
from django.utils.six.moves.urllib import parse as urlparse
import coreapi, coreschema


class CustomSchema(AutoSchema):
    def get_link(self, path, method, base_url):
        fields = self.get_path_fields(path, method)
        fields += self.get_serializer_fields(path, method)
        fields += self.get_pagination_fields(path, method)
        if self.view.action in ['list']:
            fields += self.get_filter_fields(path, method)

        manual_fields = self.get_manual_fields(path, method)
        fields = self.update_fields(fields, manual_fields)

        if fields and any([field.location in ('form', 'body') for field in fields]):
            encoding = self.get_encoding(path, method)
        else:
            encoding = None

        description = self.get_description(path, method)

        if base_url and path.startswith('/'):
            path = path[1:]

        return coreapi.Link(
            url=urlparse.urljoin(base_url, path),
            action=method.lower(),
            encoding=encoding,
            fields=fields,
            description=description
        )

views.py

class MyUserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.

    """
    model = MyUser
    serializer_class = MyUserSerializer
    queryset = MyUser.objects.all()
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = MyUserFilter
    ordering_fields = ('last_name', 'first_name', 'email', 'is_active')
    ordering = ('last_name', 'first_name')
    permission_classes = (IsAuthenticated,)
    schema = CustomSchema()

1πŸ‘

Specifying a CustomSchema for every model is not necessary.
It is possible to override the DjangoFilterBackend and prevent it from adding the schema fields for some specified actions:

class MyDjangoFilterBackend(DjangoFilterBackend):
    def get_schema_fields(self, view):
        # Customize according to your need here.
        if view.action not in ["list"]:
            return []
        return super().get_schema_fields(view)

in settings.py :

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': (
       'api.filter_backends.MyDjangoFilterBackend'
    ),
    'DEFAULT_PAGINATION_CLASS': 'api.pagination.MyPagination',
    'PAGE_SIZE': 20
} 
πŸ‘€Yohan D

Leave a comment