django rest nested relation in post/put

2019-06-19 23:10发布

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条回答
Rolldiameter
2楼-- · 2019-06-19 23:30

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

查看更多
登录 后发表回答