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(, [])
        serializer = CategoryTreeSerializer(children, many=True, context=self.context)

 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(
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter