[Answered ]-Django Rest Framework – drf-spectacular add extra models to schemas

1👍

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.

Leave a comment