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

倾然丶 夕夏残阳落幕 提交于 2021-02-19 08:33:58

问题


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?

EDIT:

Here is the model.

class Messages(models.Model):
    owner = models.OneToOneField(User, primary_key=True, related_name='user_messages', editable=False) #TODO, change owner to 'To'
    #suggested_songs = models.ForeignKey(Song, null=True, blank=True)
    suggested_songs = models.ManyToManyField(Song, related_name='suggested_songs')

回答1:


You can't create manyToMany relations without the objects already created. You must first create the objects and then make the relation. Something like:

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


来源:https://stackoverflow.com/questions/30065684/django-rest-framework-how-to-write-multiple-nested-field-serializer-for-readi

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