嵌套的序列化器概念用于发布和更新

时间:2018-09-13 05:26:02

标签: python django-rest-framework

我在python django中使用嵌套的序列化器概念。对于get()方法,我使用了如下的序列化器

class MusicianSerializer(serializers.ModelSerializer):
    album_musician = AlbumSerializer(many=True)

    class Meta:
        model = Musician
        fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician')

但是如何在不覆盖updatecreate的情况下为发布和更新概念编写嵌套的序列化器概念。

1 个答案:

答案 0 :(得分:0)

您可以在post中使用嵌套的序列化程序。但是您需要重写MusicianSerializer的create方法。

   class MusicianSerializer(serializers.ModelSerializer):
        album_musician = AlbumSerializer(many=True)

        class Meta:
            model = Musician
            fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician')

            def create(self, validated_data):
                album_musicians = validated_data.pop('album_musician')
                musician = Musician.objects.create(**validated_data)
                for album_musician  in album_musicians:
                    AlbumMusicain.objects.create(musician=musician, **album_musician)
                return musician

`