21👍
✅
You can override the get_fields
methods of serializer
and then you can change the value of that fields
class SomeDataSerializer(serializers.ModelSerializer):
some_field = serializers.CharField(max_length=100)
def get_fields(self, *args, **kwargs):
fields = super(SomeDataSerializer, self).get_fields(*args, **kwargs)
request = self.context.get('request', None)
if request and getattr(request, 'method', None) == "POST":
fields['some_field'].required = False
return fields
20👍
What I do in such situations is have a different serializer altogether that inherits from a base serializer and overrides the relevant fields. So in you case, an approach like this should work:
class CreateSerializer(serializers.Serializers):
field = serializers.CharField(max_length=100)
class UpdateSerializer(CreateSerializer):
field = serializers.CharField(max_length=100, required=False)
And in your view, return the relevant serializer:
def get_serializer_class(self):
if self.request.action == "POST":
return CreateSerializer
elif self.request.action in ["PUT", "PATCH"]:
return UpdateSerializer
I think this is a good approach to take because you might need to add additional logic in the future based on the request method. It’s also more readable than monkey patching the field’s required
attribute.
Source:stackexchange.com