Registry / web-framework / djangorestframework-dataclasses

djangorestframework-dataclasses

JSON →
library1.4.0pypypi✓ verified 28d ago

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-dataclasses
INSTALL
IMPORT
SIG · DJANGORESTFRAMEWOR
D
djangorestframework-dataclasses
web-frameworkpythonv1.4.0
Install
3.7s avg
Import
790ms
Disk
70MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v1.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.846s · 70.7MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.7s · import 0.734s · 71MB
70MB installed
● package 70MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

DataclassSerializer
✓ from rest_framework_dataclasses.serializers import DataclassSerializer

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.

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)
Debug
Known issues
breakingType 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.
fix
Upgrade `mypy` to version 1.0 or newer in your development environment or CI/CD pipelines.
affects: >= 1.3.0
breakingIn 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.
fix
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.
affects: >= 0.9.0
gotchaAs 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.
fix
When targeting Python 3.10 and newer, use `FieldType | None` instead of `typing.Optional[FieldType]` for optional fields in your dataclass definitions.
affects: >= 1.1.0 (for Python 3.10+)
gotchaThe `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.
fix
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`.
affects: >= 0.8.0
gotchaWith 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.
fix
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.
affects: >= 1.3.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'rest_framework_dataclasses'
The 'djangorestframework-dataclasses' library or its dependency 'djangorestframework' is not installed or not accessible in your Python environment.
fix
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.
NotImplementedError: Automatic serializer field deduction not supported for field 'your_field_name' on 'YourDataclass' of type '<class 'your_module.YourType'>'
The `DataclassSerializer` cannot automatically determine the appropriate Django REST Framework field type for a specific Python type used in your dataclass field.
fix
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`).
{'your_string_field': ['This field may not be blank.']}` or `{'your_list_field': ['This list may not be empty.']}
By default, Django REST Framework's `CharField` does not allow blank strings and `ListField` does not allow empty lists, even if the corresponding dataclass field is typed as optional or allows empty values.
fix
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}})`.
ValueError: mutable default <class 'list'> for field 'your_field' is not allowed: use default_factory
You have defined a mutable default value (like an empty list or dictionary) directly in a dataclass field, which causes all instances to share the same mutable object. This is a standard Python dataclasses restriction, not specific to `djangorestframework-dataclasses`.
fix
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)`.
Upgrade
Version history
1.4.0latest on PyPI · released May 14, 2025
Audit
Dependencies
djangorequiredRequired for Django integration.
djangorestframeworkrequiredThe library extends Django REST Framework serializers.
typing_extensionsoptionalRequired for older Python versions (less than 3.8) to support certain typing features.
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
1
Resources