djangorestframework-dataclasses
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.
Warnings
- breaking Type annotations in `djangorestframework-dataclasses` versions 1.3.0 and newer require `mypy` 1.0 or higher for correct validation. Older `mypy` versions may produce incorrect results or errors.
- breaking In versions 0.9.0 and later, dataclass fields with a default value or `default_factory` are automatically marked as optional (`required=False`) in the serializer. Marking a field with `typing.Optional` now only makes it nullable, not optional. If a field previously relied solely on `typing.Optional` to be non-required, it will now be considered required if it doesn't have a default value.
- gotcha As of v1.1.0, `djangorestframework-dataclasses` supports the new `X | None` union syntax (PEP 604) for specifying optional fields in Python 3.10+. This is the preferred modern way to declare optional fields.
- gotcha The `validated_data` representation no longer contains the `rest_framework.fields.empty` sentinel value for unsupplied fields since v0.8. This change reverted a breaking behavior introduced in v0.7. Code relying on the presence of `empty` for unsupplied fields will need adjustment.
- gotcha With v1.3.0, values for fields of non-list/dict composite types (e.g., `frozenset`, `OrderedDict`) are now created as their specific composite type, rather than always `list` or `dict`. This provides more accurate type handling but might affect existing code if it implicitly relied on the previous generic behavior.
Install
-
pip install djangorestframework-dataclasses
Imports
- DataclassSerializer
from rest_framework_dataclasses.serializers import DataclassSerializer
Quickstart
from dataclasses import dataclass
import datetime
from typing import Optional
from rest_framework import fields, serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
@dataclass
class UserProfile:
username: str
email: str
is_active: bool = True
date_joined: Optional[datetime.datetime] = None
class UserProfileSerializer(DataclassSerializer):
class Meta:
dataclass = UserProfile
fields = '__all__'
# Example Usage:
# Serialization
user_instance = UserProfile(
username='testuser',
email='test@example.com',
date_joined=datetime.datetime.now(datetime.timezone.utc)
)
serializer = UserProfileSerializer(user_instance)
print("Serialized data:", serializer.data)
# Deserialization
data = {
'username': 'newuser',
'email': 'new@example.com'
}
deserializer = UserProfileSerializer(data=data)
deserializer.is_valid(raise_exception=True)
new_user_profile = deserializer.validated_data
print("Deserialized object:", new_user_profile)
print("Deserialized username:", new_user_profile.username)
print("Deserialized is_active (with default):", new_user_profile.is_active)