LukaszK
LukaszK

Reputation: 179

Django Rest Framework - drf-spectacular add extra models to schemas

I used drf-spectacular and have two questions about this module.

  1. I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this? enter image description here

  2. I search a way to add custom models to Schemas but without connected this with endpoints. I see that i can add custom Schema by:

"""

inline_serializer(
               name='PasscodeResponse',
               fields={
                   'passcode': serializers.CharField(),
               }
           ), 

But don't know where to put this.

I wanna just see this in this Schemas like on screen:

enter image description here

Upvotes: 1

Views: 1325

Answers (1)

zamoosh
zamoosh

Reputation: 87

Use generic view to automatically implement this:

from rest_framework.generics import GenericAPIView

example of my view:

class CategoryDetails(GenericAPIView):
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUser]
    http_method_names = ['get', 'put']

    def get_object(self, pk):
        try:
            return Category.objects.get(pk=pk)
        except Category.DoesNotExist:
            return None

    def get(self, request, pk):
        category = self.get_object(pk)
        if category:
            serializer = CategorySerializer(category)
            return Response(serializer.data)
        else:
            return Response({}, status=status.HTTP_200_OK)


GenericAPIView will generate both schema and example value

Or if you using APIView class, you can achieve this by adding this function to you APIView class: get_serializer. this function gonna generate a blue print of your instance if your editing it in browse able page or add this blueprint in add section.

FOR EXAMPLE:

def get_serializer(self, instance=None):
    """this method generate a JSON blueprint of object in Raw data > content (the text area)"""
    if instance:
        serializer_class = self.serializer_class
        return serializer_class(instance)
    return CategorySerializer()

Don't forget to add the serializer_class class property to your APIView.

Upvotes: 1

Related Questions