django-rest-frameworkdjango-mptt

How to serialize the django-mptt efficiently with Django Rest Framework?


serializers.py

class RecursiveField(serializers.Serializer):
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

class CategorySerializer(serializers.ModelSerializer):
    children = RecursiveField(many=True)
    class Meta:
        model = Category
        fields=('id', 'title', 'description', 'children',)

It returns response data like:

    {
      "id": 1,
      "title": "Bike",
      "description": "",
      "children": []
    },
    {
      "id": 2,
      "title": "Car",
      "description": "",
      "children": [
        {
          "id": 3,
          "title": "Honda",
          "description": "",
          "children": []
        }
      ]
    },
    {
      "id": 3,
      "title": "Honda",
      "description": "",
      "children": []
    }

As shown above, category with ID: 3 has been repeated. If a category is some category's child then I don't want it to show separately again. I want response data like this:

    {
      "id": 1,
      "title": "Bike",
      "description": "",
      "children": []
    },
    {
      "id": 2,
      "title": "Car",
      "description": "",
      "children": [
        {
          "id": 3,
          "title": "Honda",
          "description": "",
          "children": []
        }
      ]
    }

Can someone help me to solve it?


Solution

  • You can just return the roots, so just roots will be returned not the children of the of parents, this is how I did.

    class CategoryManager(TreeManager):
        def viewable(self):
            queryset = self.get_queryset().filter(level=0)
            return queryset
    

    In Category models.

    objects = CategoryManager()
    

    And then in views I used it like this:

    queryset = Category.objects.viewable()