I have implemented Foreign key to fetch a list of genres for movies using StringRelatedField in DRF. This however does not work while POST. I get StringRelatedField.to_internal_value() must be implemented as error. Can anyone help me?
models.py
class Movies(models.Model):
movie_id = models.AutoField(primary_key=True)
movie_name = models.CharField(max_length =200)
director = models.CharField(max_length = 100)
popularity = models.FloatField(max_length = 3)
imdb_score = models.FloatField(max_length = 10)
def __unicode__(self):
return '%s%s%d%d' % (self.movie_name,self.director,self.popularity,self.imdb_score)
class Genre(models.Model):
genre_id = models.AutoField(primary_key=True)
movie_name =models.ForeignKey(Movies, blank=True, null=True, on_delete=models.SET_NULL,related_name='genres')
genre = models.CharField(max_length =40)
def __unicode__(self):
return '%s%s' % (self.genre,self.movie_name)
views.py
class MovieList(viewsets.ViewSet):
def list(self,request):
try:
movie_list = Movies.objects.all()
serializer = MovieSerializer(movie_list, many=True)
username = request.session['username']
user_role = request.session['role']
context = {'username': username, 'user_role': user_role, 'movie_list': serializer.data}
return render(request, 'imdb/movie-list.html', context)
except KeyError:
pass
return HttpResponseRedirect(reverse('imdb:login'))
class AddMovie(APIView):
def post(self, request, format='json'):
data = request.data
serializer = MovieSerializer(data =request.data)
#print serializer
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
urls.py
urlpatterns = patterns('',
url(r'^$', views.login, name='login'),
url(r'^home/$', views.home, name='home'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^movie-list/$', views.MovieList.as_view({'get':'list'}),name ='movie-list'),
url(r'^add-movie/$', views.AddMovie.as_view(),name ='add-movie') )
serializer.py
class MovieSerializer(serializers.ModelSerializer):
genres = serializers.StringRelatedField(many=True)
class Meta:
model = Movies
fields = ('movie_name','director','popularity','imdb_score','genres')
StringRelatedField is read only. I had to use nested serilaizers.
Another way is to implement
to_internal_value()
. However I agree with the author's opinion. I reluctantly implemented this just because of the existence of a technical debt in our project.This is what I did, but I think it depends on the situation.
And the serializer looks like that: