Django rest nested relationship in post / put

I am new to django rest api development. I have two models, one category and the other subcategories. Here are my models.

class Category(models.Model): title = models.Charfield() brief = models.TextField() subcategories = model.ManyToManyField('Subcategory', blank=True) 

My serializer class

 class CategorySerializer(serializers.ModelSerializer): title= serializer.Charfield() subcategories = Relatedfield(many=True) 

Now in sight

 def post(self, request, format = None): data=request.DATA serialize= CategorySerializer(data=request.DATA) if serializer.valid(): serializer.save() 

How to save nested data like {'title':"test",'subscategories':[{'description':'bla bla bla'},{'description':'test test'}]} in the post method.

I read this in the documentation

Note. Nested serializers are read-only because there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. To read / write a view, you should always use a flat view using one of the RelatedField subclasses.

Please let me suggest which is the right way or solution to make the nested post / put relationship in django rest.

+6
source share
1 answer

Have you tried to create a SubCategorySerializer and added this as a field to the CategorySerializer ?

 class SubcategorySerializer(serializers.ModelSerializer): class Meta: model = Subcategory class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategorySerializer(many=True) 

Docs: http://django-rest-framework.org/api-guide/relations.html#nested-relationships

+2
source

Source: https://habr.com/ru/post/947461/


All Articles