6
votes

I am new in django rest api developement. I have two models one is category and another is subcategories. Here is 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 view

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 post method.

I have read this in documentation

Note: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the RelatedField subclasses.

Please let me suggest which is right way or solution to do nested relation post/put in django rest.

1
I need help regarding django rest framework(api) Posting data for m:m relationship and get added into database.Rupesh Patil

1 Answers

3
votes

Have you tried creating a SubCategorySerializer and adding this as a field on 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