Different serializers for different actions.

This commit is contained in:
Josh Washburne 2018-04-02 16:54:53 -04:00
parent ddbcf5c96f
commit aaad64dc39
2 changed files with 27 additions and 4 deletions

View file

@ -27,10 +27,22 @@ class GameSerializer(serializers.ModelSerializer):
fields = ('id', 'title') fields = ('id', 'title')
class SongSerializer(serializers.ModelSerializer): class SongCreateSerializer(serializers.ModelSerializer):
artists = ArtistFullnameSerializer(many=True)
class Meta: class Meta:
model = Song model = Song
fields = ('id', 'album', 'artists', 'published_date', 'game', fields = ('id', 'album', 'artists', 'published_date', 'game',
'num_played', 'last_played', 'length', 'song_type', 'title') 'num_played', 'last_played', 'length', 'song_type', 'title')
def create(self, validated_data):
artists_data = validated_data.pop('artists')
song = Song.objects.create(**validated_data)
print(artists_data)
for artist_data in artists_data:
print(artist_data)
song.artists.add(artist_data)
song.save()
return song
class SongSerializer(SongCreateSerializer):
artists = ArtistFullnameSerializer(many=True)

View file

@ -3,7 +3,8 @@ from rest_framework import viewsets
from radio.models import Album, Artist, Game, Song from radio.models import Album, Artist, Game, Song
from ..permissions import IsAdminOrReadOnly from ..permissions import IsAdminOrReadOnly
from ..serializers.radio import (AlbumSerializer, ArtistSerializer, from ..serializers.radio import (AlbumSerializer, ArtistSerializer,
GameSerializer, SongSerializer) GameSerializer, SongSerializer,
SongCreateSerializer)
class AlbumViewSet(viewsets.ModelViewSet): class AlbumViewSet(viewsets.ModelViewSet):
@ -28,3 +29,13 @@ class SongViewSet(viewsets.ModelViewSet):
permission_classes = [IsAdminOrReadOnly] permission_classes = [IsAdminOrReadOnly]
queryset = Song.objects.all() queryset = Song.objects.all()
serializer_class = SongSerializer serializer_class = SongSerializer
def get_serializer_class(self):
'''
Choose a different serializer based on what action is chosen.
(Thanks to https://stackoverflow.com/questions/22616973/)
'''
if self.action == 'create':
return SongCreateSerializer
return SongSerializer