I'm trying to create objects just by getting a json that have the objects nested in it,for example, I have a model with only one field that is name and im getting this json
{"name":"category1",
"children":[{
"name":"category1.1",
"children":[]},
{"name":"category1.2",
"children":[{"name":"category1.2.1",
"children":[]}]
}
]
}
What i'm trying to achieve is to read this,and create category objects that reference its parent or its children, I've tried multiple solutions inspired from these answers but I can't seem to get close to getting the job done(Django rest framework nested self-referential objects -- How to create multiple objects (related) with one request in DRF?)
I've tried having the model with only name and a foreign key that reference the category itself,and I added recursive field to my serializer like this:
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):
subcategories = RecursiveField(many=True,allow_null=True)
class Meta:
model = Category
fields = ['name','subcategories']
def create(self, validated_data):
category = None
if len(validated_data['subcategories'])==0:
category = Category.objects.create(name=validated_data['name'])
else:
for i in range(len(validated_data['subcategories'])):
child = validated_data['subcategories']
child_list = list(child.items())
subcat = child_list[1]
if len(subcat)==0:
subcategory = Category.objects.create(name=child.get('name'))
category = Category.objects.create(name=validated_data['name'],children=subcategory)
return category
The best I got with this solution is being able to create the parent object,but I wasn't able to get the children objects instead I got an empty OrderedDict() (I only tried this solution to see if i can access the children but apparently i can't,I get an empty OrderedDict() in child variable)
Am I looking at this from the wrong prespective? or is my model architecture not suitable for this? if not,what am i doing wrong