oxan / djangorestframework-dataclasses

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

Serializing breaks with Optional[List[Something]] #26

Closed wkrueger closed 3 years ago

wkrueger commented 3 years ago

adapted sample

@dataclass
class MaybeBalls:
    balls: Optional[List[str]]

class MaybeBallsSerializer(DataclassSerializer):
    class Meta:
            dataclass = MaybeBalls

input = {}
serializer = MaybeBallsSerializer(data=input)
print(serializer.data) # will fail

yields something like

  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 632, in data
    ret = super().data
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 320, in data
    self._data = self.to_representation(self.validated_data)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 599, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/fields.py", line 1692, in to_representation
    return [self.child.to_representation(item) if item is not None else None for item in data]
TypeError: 'type' object is not iterable

it tries to iterate over a

wkrueger commented 3 years ago

Update: I should be using .validated_data not .data. With validated_data it works fine.

oxan commented 3 years ago

This is actually a side-effect of #27, so closing in favor of that issue.