How to serialize hierarchical relationship in Django REST

前端 未结 2 785
时光取名叫无心
时光取名叫无心 2021-02-09 07:53

I have a Django model that is hierarchical using django-mptt, which looks like:

class UOMCategory(MPTTModel, BaseModel):
    \"\"\"
        This represents categ         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 08:21

    Simple DRF API view using MPTT cache and DRF serializer.

    from rest_framework import serializers
    from rest_framework.generics import GenericAPIView
    from rest_framework.response import Response
    
    from events.models import Category
    
    
    class CategorySerializer(serializers.ModelSerializer):
        class Meta:
            model = Category
            fields = (
                "name",
                "slug",
            )
    
    
    class CategoryTreeView(GenericAPIView):
        serializer_class = CategorySerializer
    
        def get(self, request, *args, **kwargs):
            root_nodes = Category.objects.all().get_cached_trees()
    
            data = []
            for n in root_nodes:
                data.append(self.recursive_node_to_dict(n))
    
            return Response(data)
    
        def recursive_node_to_dict(self, node):
            result = self.get_serializer(instance=node).data
            children = [self.recursive_node_to_dict(c) for c in node.get_children()]
            if children:
                result["children"] = children
            return result
    

提交回复
热议问题