django rest nested relation in post/put

北城余情 提交于 2019-12-23 09:32:58

问题


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:


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



来源:https://stackoverflow.com/questions/17146412/django-rest-nested-relation-in-post-put

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!