django rest framework create nested objects “Models” by POST

后端 未结 4 892
暖寄归人
暖寄归人 2020-12-23 12:29

I\'m trying POST a new a Nested Object, the problem is just create the \"top\" object (Playlist), but don\'t create the \"ChannelItem\"...

My Models:



        
4条回答
  •  感情败类
    2020-12-23 12:41

    For me, I have a hybrid workaround that I'm OK with. Namely, create a view that has:

    • the ManyToMany field in its un-nested serializer form
    • alias the nested ManyToMany field into a variable with _objs as the suffix and specify it as as read only
    • when you PUT back to the server reconcile the two aliased fields and store the result in the un-nested serializer field

    e.g.

    class MSerializer(serializers.HyperlinkedModelSerializer):
        foo_objs = TempSensorSerializer(source='foos', many=True, allow_add_remove=True,required=False,read_only=True)
        class Meta:
            model = M
            fields = ('url', 'foos', 'foo_objs')
    

    I don't love this solution, but it beats trying to separately query and collate the nested fields after retrieving the initial container.

提交回复
热议问题