oxan / djangorestframework-dataclasses

Dataclasses serializer for Django REST framework
BSD 3-Clause "New" or "Revised" License
431 stars 28 forks source link

many=True and Optional field with default value sets <class 'rest_framework.fields.empty'> instead of default value of dataclass #39

Closed dineshtrivedi closed 3 years ago

dineshtrivedi commented 3 years ago

When using many=True in a Serializer Generated by DataclassSerializer, the Optional Field (the id field in the example below) will have value of <class 'rest_framework.fields.empty'>.

In the example below the expected value is None since it is the default value:

@dataclass
class HelloWorldManyExample:
    name: str
    mobile_number: str
    id_only_optional: Optional[int]
    id_only_default: int = None
    id_default_and_optional: Optional[int] = None

class HelloWorldManyInput(DataclassSerializer):
    class Meta:
        dataclass = HelloWorldManyExample

class HelloWorldManyViewDataclass(APIView):
    parser_classes = (CamelCaseJSONParser,)
    renderer_classes = (CamelCaseJSONRenderer,)

    @swagger_auto_schema(request_body=HelloWorldManyInput(many=True))
    def post(self, request):
        hello_world_many_data = HelloWorldManyInput(data=request.data, many=True)
        hello_world_many_data.is_valid(raise_exception=True)
        return JsonResponse({"received": [asdict(data) for data in hello_world_many_data.validated_data]})

I have a project running the example above with swagger, you can check here in case that helps - https://github.com/dineshtrivedi/django-architecture/tree/drf-dataclass-issue-1

What do you think?

dineshtrivedi commented 3 years ago

I wanted to create the issue and add a PR, but work has been very busy. Maybe I can get to this over the weekend.

oxan commented 3 years ago

What do you think?

This is a bug, but I'm not sure how to solve it (yet).