Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional serializer field in Django Rest Framework

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

The doc says required=False to have None values, not required=None.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading