このメソッドを使用して、多対多の関係のネストされたシリアル化で更新を処理しています。
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を指定しないと機能しない2回目の試み:
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