mardi 5 mai 2015

Django Rest Framework - how to write multiple nested field serializer (for reading & writing)

I'm trying to write a "def create" method to perform nested serialization for multiple objects.

    def create(self, validated_data):
        suggested_songs_data = validated_data.pop('suggested_songs')
        suggest_song_list = list()
        for song_data in suggested_songs_data:
            song = Song.objects.create(**song_data)
            suggest_song_list.append(song)          
        message = Messages.objects.create(suggested_songs=suggest_song_list, **validated_data)
        return message

Here is my schema:

class MessagesSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.IntegerField(source='pk', read_only=True)
    suggested_songs = SongSerializer(many=True)

    class Meta:
        model = Messages
        fields = ('id','owner','url','suggested_songs',)
        #fields = ('id','url','suggested_songs',)

class SongSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Song
        fields =('id','title','artist','album','albumId','num_votes','cleared')
        read_only_fields = ('song_id')

But I am getting this error

Cannot assign "[<Song: Song object>, <Song: Song object>]":     "Messages.suggested_songs" must be a "Song" instance.

Any advice?

Aucun commentaire:

Enregistrer un commentaire