How to serialize a Django MPTT family and keep it hierarchical?


Wed Jun 16 2021 14:09:00 GMT+0000 (Coordinated Universal Time)

Saved by @kibet

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(