1👍
✅
Turns out inside the serializer I need to use:
self.context.get("request").parser_context["kwargs"]["album_id"]
0👍
Instead of passing album_id
in context
, you can pass album_id
via serializer.save()
and DRF will automatically create Song
object with album_id
field.
You need to make some changes to your code.
In your views, you don’t need to pass context
to the serializer. You should instead pass album_id
in serializer.save()
.
@detail_route(methods=['post', 'get'], serializer_class=SongSerialiser)
def get_so(self, request, album_id=None):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save(album_id=album_id) # pass album_id here
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response({"detail": serializer.errors,
"status_code": status.HTTP_400_BAD_REQUEST})
Secondly, you can convert SongSerialiser
to ModelSerializer
having only the field song_name
without adding the create()
method.
class SongSerialiser(serializers.ModelSerializer): # use modelserializer
class Meta:
model = Song
fields = ['song_name'] # only define song_name field
When serializer.save()
is called, DRF will create Song
object with song_name
from request.data
and album_id
from extra kwarg we passed in .save()
.
Source:stackexchange.com