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
# 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)
content_copyCOPY
Comments