【问题标题】:Django Rest Framework - how to write multiple nested field serializer (for reading & writing)Django Rest Framework - 如何编写多个嵌套字段序列化器(用于读取和写入)
【发布时间】:2016-09-02 22:48:17
【问题描述】:

我正在尝试编写一个“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')

【问题讨论】:

  • 听起来你的Messages 模型有一个suggested_songs 字段,它是ForeignKey 而不是ManyToMany
  • 啊,是的,我是。我会用模型更新问题。
  • 'suggested_songs' 是一个无效的关键字参数,此函数现在在尝试发布数据后显示。
  • 您还有什么建议吗?我讨厌出错,但我有点卡在这里。

标签: python django django-rest-framework django-serializer


【解决方案1】:

如果没有已创建的对象,您将无法创建 manyToMany 关系。您必须首先创建对象,然后建立关系。 比如:

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

【讨论】:

  • 是的,我要得到这个解决方案,感谢他完美的工作。根据我的要求......非常感谢非常感谢这个ans。 @educol
猜你喜欢
  • 2015-03-20
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多