gpt4 book ai didi

python - Django Rest Framework - 如何编写多个嵌套字段序列化器(用于读取和写入)

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:11 31 4
gpt4 key购买 nike

我正在尝试编写一个“def create”方法来对多个对象执行嵌套序列化。

    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

这是我的架构:

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')

但我收到此错误

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

有什么建议吗?

编辑:

这是模型。

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')

最佳答案

如果没有创建对象,则无法创建多对多关系。您必须首先创建对象,然后建立关系。像这样的东西:

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

关于python - Django Rest Framework - 如何编写多个嵌套字段序列化器(用于读取和写入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065684/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com