1👍
You can create another serializer AreaPutSerializer
which will inherit from AreaSerializer
for handling PUT
requests.
In AreaPutSerializer
, we will set map_id
field as read_only
using extra_kwargs
option. Doing this will ensure that in PUT
requests, map_id
field will be included in the API output but not be used in write operations.
class AreaSerializer(serializers.ModelSerializer):
x_axis = serializers.FloatField()
y_axis = serializers.FloatField()
map_id = serializers.IntegerField(source='area_map_id')
class AreaPutSerializer(AreaSerializer):
class Meta(AreaSerializer.Meta):
extra_kwargs = {'map_id': {'read_only':True}}
In your view, then you can add a get_serializer_class
method which will return the serializer class to be used depending on the request method.
def get_serializer_class(self):
if self.request.method == 'PUT':
return AreaPutSerializer
return AreaSerializer
Source:stackexchange.com