# 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 @detail_route() 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: children_dict[descendant.get_parent().pk].append(descendant) context = self.get_serializer_context() context['children'] = children_dict serializer = CategoryTreeSerializer(category, context=context) return Response(serializer.data)
Preview:
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