django rest framework create nested objects “Models” by POST

后端 未结 4 894
暖寄归人
暖寄归人 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:47

    If someone needs a quick-and-dirty solution for that, I came up with this one I'll be temporary using in a project:

    class NestedManyToManyField(serializers.WritableField):
        def to_native(self, value):
            serializer = self.Meta.serializer(value.all(), many=True, context=self.context)
            return serializer.data
        def from_native(self, data):
            serializer = self.Meta.serializer(data=data, many=True, context=self.context)
            serializer.is_valid()
            serializer.save()
            return serializer.object
        class Meta:
            serializer = None
    

    Then create your own subclass of NestedManyToManyField:

    class TopicNestedSerializer(NestedManyToManyField):
        class Meta:
            serializer = MyOriginalSerializer
    

    An example of MyOriginalSerializer:

    class MyOriginalSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.MyModel
            fields = ('id', 'title',)
    

    This works fine for me so far. But be aware there are clean fixes coming:

    • https://github.com/tomchristie/django-rest-framework/issues/960
    • https://github.com/tomchristie/django-rest-framework/pull/817

提交回复
热议问题