Reputation: 425
I recently began to learn DRF library, I do not understand how in this example make method update in AlbumSerializer to save foreign key. Thank you in advance.
Upvotes: 1
Views: 49
Reputation: 9235
It's basic example serializer, but if you need a suggestion, then this may help you. A simple update method for the serializer,
def update(self, instance, validated_data):
tracks = validated_data.pop('tracks')
instance.album_name = validated_data.get('title', instance.album_name)
instance.artist = validated_data.get('artist', instance.artist)
instance.save()
for track in tracks:
new_track = Track.objects.get(album=instance, order=track['order'])
new_track.title = track.get('title', new_track.title)
new_track.duration = track.get('duration', new_track.duration)
new_track.save()
return instance
Upvotes: 1