-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement AlbumSerializer in music app and update docs
Expanded the existing service of the music app by introducing the AlbumSerializer. This includes defining required fields, and creating methods for 'create' and 'update' operations. The documentation is correspondingly updated to explain the new AlbumSerializer and its methods.
- Loading branch information
1 parent
eb7fa0f
commit fb54dfc
Showing
2 changed files
with
77 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,37 @@ | ||
from rest_framework import serializers | ||
|
||
from music.models import Artist | ||
from music.models import Artist, Album | ||
|
||
|
||
class ArtistSerializer(serializers.HyperlinkedModelSerializer): | ||
class Meta: | ||
model = Artist | ||
fields = ['name'] | ||
|
||
|
||
# You could use the HyperlinkedModelSerializer here but | ||
# want you to know how a plain serializer works | ||
# class AlbumSerializer(serializers.HyperlinkedModelSerializer): | ||
class AlbumSerializer(serializers.Serializer): | ||
title = serializers.CharField() | ||
artist = ArtistSerializer() # Serializers inherits from Field, so it can be used as fields too | ||
release_year = serializers.IntegerField() | ||
|
||
class Meta: | ||
fields = ['title', 'artist', 'release_year'] | ||
|
||
def create(self, validated_data): | ||
artist_data = validated_data.pop('artist') | ||
artist, created = Artist.objects.get_or_create(name=artist_data['name']) | ||
return Album.objects.create(artist=artist, **validated_data) | ||
|
||
def update(self, album, validated_data): | ||
artist_data = validated_data.pop('artist') | ||
artist, created = Artist.objects.get_or_create(name=artist_data['name']) | ||
|
||
album.title = validated_data.get('title', album.title) | ||
album.release_year = validated_data.get('release_year', album.release_year) | ||
album.artist = artist | ||
album.save() | ||
|
||
return album |