How can I set a serializer field to optional in Django REST Framework?
I have the following serializer:
class IdSerializer(serializers.Serializer):
id = serializers.IntegerField(required=None)
required
is set to None
following the docs.
And my view:
class MyView(APIView):
serializer_class = PostIdSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
post_id = serializer.validated_data.get("id")
return Response()
**However, when I send a POST request to the endpoint, I get the error:
{
"id": [
"This field is required."
]
}
How can I allow no id
to be sent?
CodePudding user response:
The doc says required=False
to have None values, not required=None
.