Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest nested relation in post/put

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.

like image 804
Rupesh Patil Avatar asked Jun 17 '13 11:06

Rupesh Patil


1 Answers

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

like image 168
mynameistechno Avatar answered Oct 23 '22 03:10

mynameistechno