# serializers.py
class CategoryTreeSerializer(ModelSerializer):
    children = SerializerMethodField(source='get_children')
    class Meta:
        fields = ('children',)  # add here rest of the fields from model 

    def get_children(self, obj):
        children = self.context['children'].get(obj.id, [])
        serializer = CategoryTreeSerializer(children, many=True, context=self.context)
        return serializer.data

 # views.py
 class CategoryViewSet(viewsets.ModelViewSet):

    queryset = Category.objects.all()
    serializer_class = CategoryTreeSerializer

    def tree(self, request, pk=None):
        Detail route of an category that returns it's descendants in a tree structure.
        category = self.get_object()
        descendants = category.get_descendants() # add here any select_related/prefetch_related fields to improve api performance

        children_dict = defaultdict(list)
        for descendant in descendants:

        context = self.get_serializer_context()
        context['children'] = children_dict
        serializer = CategoryTreeSerializer(category, context=context)

        return Response(serializer.data)