我正在使用此方法来处理多对多关系的嵌套序列化中的更新。
def update(self, instance, validated_data):
songs = validated_data.pop('suggested_songs')
updated_instance = super(MessagesSerializer, self).update(instance, validated_data)
updated_instance.save()
for song_data in songs:
s = Song(**song_data)
s.save()
updated_instance.suggested_songs.add(s)
但是我注意到,在尝试更新数据时,会发生重复的歌曲,而不是编辑现有的歌曲。
我认为有一种方法可以在添加新的之前清除“suggested_songs”,但理想情况下我会正确编辑现有数据,我该如何实现?
修改
除非我指定ID,否则我的第二次尝试无效:
def update(self, instance, validated_data):
suggested_songs_data = validated_data.pop('suggested_songs')
updated_instance = super(MessagesSerializer, self).update(instance, validated_data)
updated_instance.save()
for song_data in suggested_songs_data:
#songID = song_data.pop('id') # Grabbing the song ID so that we can check if the ID already exists.
#print(songID)
s = Song(**song_data)
print(song_data)
print(instance)
print("HELLO")
print(suggested_songs_data)
# If the song already exists we want to edit
print("+++ DEBUG ------------------------- DEBUG +++")
s.id = '20'
print(s.id)
print(s.title)
if Song.objects.filter(id = s.id).exists():
print("FOUND OBJECT")
# If the object exists, then we should edit it.
foundSong = Song.objects.get(id=s.id)
print(foundSong.title)
# We should be editing song.
foundSong.title = s.title
foundSong.artist = s.artist
foundSong.album = s.album
foundSong.albumId = s.albumId
foundSong.num_votes = s.num_votes
foundSong.cleared = s.cleared
foundSong.save()
else:
# no object satisfying query exists, so lets create a new one.
s.save()
updated_instance.suggested_songs.add(s)
return updated_instance