oxan / djangorestframework-dataclasses

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

Serializer initializing dataclass with non init fields #71

Closed aryan-curiel closed 1 year ago

aryan-curiel commented 1 year ago

Hi there!

I have a situation here, that I think might be a bug, or maybe I just haven't found a way to solve it since I'm still new with the package.

Example:

from dataclasses import dataclass, field

@dataclass
class A:
    foo: str
    bar: str = field(init=False)

from rest_framework_dataclasses.serializers import DataclassSerializer

class ASerializer(DataclassSerializer):
    class Meta:
        dataclass = A

The previous code (adapted and simplified from my real code), raises the exception when trying to validate:

TypeError: A.__init__() got an unexpected keyword argument 'bar'

Proposal: In the following line of code, where the dataclass is being instantiated, it might be a good idea to exclude from the empty_values, those fields with init=False.