Add/Remove artists for song objects in the API. Code cleanup.

This commit is contained in:
Josh Washburne 2018-04-03 16:24:54 -04:00
parent 5bcf6c72d9
commit 6dd4fa72ec
2 changed files with 45 additions and 4 deletions

View file

@ -27,12 +27,15 @@ class GameSerializer(serializers.ModelSerializer):
fields = ('id', 'title')
class SongCreateSerializer(serializers.ModelSerializer):
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = ('id', 'album', 'artists', 'published_date', 'game',
'num_played', 'last_played', 'length', 'song_type', 'title')
class SongCreateSerializer(SongSerializer):
def create(self, validated_data):
artists_data = validated_data.pop('artists')
song = Song.objects.create(**validated_data)
@ -42,5 +45,11 @@ class SongCreateSerializer(serializers.ModelSerializer):
return song
class SongSerializer(SongCreateSerializer):
class SongRetrieveSerializer(SongSerializer):
artists = ArtistFullnameSerializer(many=True)
class SongArtistsListSerializer(serializers.Serializer):
artists = serializers.ListField(child=serializers.IntegerField(),
min_length=1,
max_length=10)

View file

@ -1,10 +1,14 @@
from rest_framework import viewsets
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from radio.models import Album, Artist, Game, Song
from ..permissions import IsAdminOrReadOnly
from ..serializers.radio import (AlbumSerializer, ArtistSerializer,
GameSerializer, SongSerializer,
SongCreateSerializer)
SongArtistsListSerializer,
SongCreateSerializer, SongRetrieveSerializer)
class AlbumViewSet(viewsets.ModelViewSet):
@ -38,4 +42,32 @@ class SongViewSet(viewsets.ModelViewSet):
'''
if self.action == 'create':
return SongCreateSerializer
if self.action in ['list', 'retrieve']:
return SongRetrieveSerializer
return SongSerializer
def _change_artists(self, request, remove=False):
song = self.get_object()
serializer = SongArtistsListSerializer(data=request.data)
if serializer.is_valid():
artists = Artist.objects.filter(pk__in=serializer.data['artists'])
for artist in artists:
if remove:
song.artists.remove(artist)
else:
song.artists.add(artist)
song.save()
message = 'Artists {} song.'.format(('added to',
'removed from')[remove])
return Response({'detail': message})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@action(methods=['post'], detail=True, permission_classes=[IsAdminUser])
def add_artists(self, request, pk=None):
return self._change_artists(request)
@action(methods=['post'], detail=True, permission_classes=[IsAdminUser])
def remove_artists(self, request, pk=None):
return self._change_artists(request, remove=True)