djangorestframework-dataclasses (current version 1.4.0) is an active Python library providing a dataclasses serializer for Django REST Framework (DRF). It offers automatic field generation for Python dataclasses, mirroring the functionality of DRF's `ModelSerializer` for Django models, making it easier to define API schemas using dataclasses. The library is actively maintained with regular releases.
pip install djangorestframework-dataclassesVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a dataclass, create a `DataclassSerializer` for it, and then use the serializer to convert a dataclass instance into a dictionary (serialization) and to create a dataclass instance from a dictionary (deserialization), including handling default values.
Upgrade `mypy` to version 1.0 or newer in your development environment or CI/CD pipelines.
Ensure fields intended to be optional have a default value (e.g., `field: str = ''` or `field: Optional[str] = None`) or `default_factory`. For explicit control, use `extra_kwargs={'field_name': {'required': False}}` in the `Meta` class.When targeting Python 3.10 and newer, use `FieldType | None` instead of `typing.Optional[FieldType]` for optional fields in your dataclass definitions.
Modify code to check for the absence of a key in `validated_data` using `if 'key' not in validated_data:` instead of checking for `value is rest_framework.fields.empty`.
Review serialization/deserialization logic for custom or less common composite types. If specific serialization behavior is needed, use the `serializer_field_mapping` dictionary in the serializer's `Meta` class to override the field for those types.
Install the library and its dependencies using pip: `pip install djangorestframework-dataclasses djangorestframework`. Also ensure 'rest_framework' is in your Django project's INSTALLED_APPS.
Explicitly define the serializer field for the problematic type in your `DataclassSerializer` class or extend the `serializer_field_mapping` in the Meta class. Example: `your_field_name = serializers.FileField()` or `your_field_name: Annotated[InMemoryUploadedFile, serializers.FileField()]` (if using `typing.Annotated`).
Explicitly set `allow_blank=True` for string fields or `allow_empty=True` for list fields in your serializer definition. You can do this by overriding the field directly on the serializer or by passing `serializer_kwargs` in the dataclass field metadata, e.g., `field(metadata={'serializer_kwargs': {'allow_blank': True}})`.Use `dataclasses.field(default_factory=...)` to provide a callable (e.g., `list` or `dict`) that creates a new mutable object for each instance. Example: `your_field: List[str] = field(default_factory=list)`.