[Fixed]-Django nested relation data

1👍

You can write additional serializer for child category:

class ChildrenSerializer(serializers.ModelSerializer):

    class Meta:
         model = Category
         fields = ('id_category', 'name', 'parent')

class CategorySerializer(serializers.ModelSerializer):
    children = ChildrenSerializer(many=True)

    class Meta:
        model = Category
        fields = ('id_category', 'name', 'parent', 'children')

You could also show nested models with depth option:

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        depth = 1
        fields = ('id_category', 'name', 'parent', 'children')

Leave a comment