{"id":3467,"library":"djangorestframework-dataclasses","title":"djangorestframework-dataclasses","description":"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.","status":"active","version":"1.4.0","language":"python","source_language":"en","source_url":"https://github.com/oxan/djangorestframework-dataclasses","tags":["django","rest-framework","dataclasses","serialization","api"],"install":[{"cmd":"pip install djangorestframework-dataclasses","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for Django integration.","package":"django","optional":false},{"reason":"The library extends Django REST Framework serializers.","package":"djangorestframework","optional":false},{"reason":"Required for older Python versions (less than 3.8) to support certain typing features.","package":"typing_extensions","optional":true}],"imports":[{"symbol":"DataclassSerializer","correct":"from rest_framework_dataclasses.serializers import DataclassSerializer"}],"quickstart":{"code":"from dataclasses import dataclass\nimport datetime\nfrom typing import Optional\n\nfrom rest_framework import fields, serializers\nfrom rest_framework_dataclasses.serializers import DataclassSerializer\n\n@dataclass\nclass UserProfile:\n    username: str\n    email: str\n    is_active: bool = True\n    date_joined: Optional[datetime.datetime] = None\n\nclass UserProfileSerializer(DataclassSerializer):\n    class Meta:\n        dataclass = UserProfile\n        fields = '__all__'\n\n# Example Usage:\n# Serialization\nuser_instance = UserProfile(\n    username='testuser',\n    email='test@example.com',\n    date_joined=datetime.datetime.now(datetime.timezone.utc)\n)\nserializer = UserProfileSerializer(user_instance)\nprint(\"Serialized data:\", serializer.data)\n\n# Deserialization\ndata = {\n    'username': 'newuser',\n    'email': 'new@example.com'\n}\ndeserializer = UserProfileSerializer(data=data)\ndeserializer.is_valid(raise_exception=True)\nnew_user_profile = deserializer.validated_data\nprint(\"Deserialized object:\", new_user_profile)\nprint(\"Deserialized username:\", new_user_profile.username)\nprint(\"Deserialized is_active (with default):\", new_user_profile.is_active)\n","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade `mypy` to version 1.0 or newer in your development environment or CI/CD pipelines.","message":"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.","severity":"breaking","affected_versions":">= 1.3.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">= 0.9.0"},{"fix":"When targeting Python 3.10 and newer, use `FieldType | None` instead of `typing.Optional[FieldType]` for optional fields in your dataclass definitions.","message":"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.","severity":"gotcha","affected_versions":">= 1.1.0 (for Python 3.10+)"},{"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`.","message":"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.","severity":"gotcha","affected_versions":">= 0.8.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">= 1.3.0"}],"env_vars":null,"search_vec":"'1.4.0':9 'activ':12,54 'api':47,65 'automat':26 'current':7 'dataclass':3,6,17,31,50,63 'defin':46 'django':20,40,59 'djangorestframework':2,5 'djangorestframework-dataclass':1,4 'drf':23,36 'easier':44 'field':27 'framework':22,62 'function':34 'generat':28 'librari':14,52 'maintain':55 'make':42 'mirror':32 'model':41 'modelseri':38 'offer':25 'provid':15 'python':13,30 'regular':57 'releas':58 'rest':21,61 'rest-framework':60 'schema':48 'serial':18,64 'use':49 'version':8","created_at":"2026-04-11T17:30:52.709501+00:00","updated_at":"2026-04-16T14:37:19.147720+00:00","problems":[{"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.","cause":"The 'djangorestframework-dataclasses' library or its dependency 'djangorestframework' is not installed or not accessible in your Python environment.","error":"ModuleNotFoundError: No module named 'rest_framework_dataclasses'"},{"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`).","cause":"The `DataclassSerializer` cannot automatically determine the appropriate Django REST Framework field type for a specific Python type used in your dataclass field.","error":"NotImplementedError: Automatic serializer field deduction not supported for field 'your_field_name' on 'YourDataclass' of type '<class 'your_module.YourType'>'"},{"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}})`.","cause":"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.","error":"{'your_string_field': ['This field may not be blank.']}` or `{'your_list_field': ['This list may not be empty.']}"},{"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)`.","cause":"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`.","error":"ValueError: mutable default <class 'list'> for field 'your_field' is not allowed: use default_factory"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.4.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/oxan/djangorestframework-dataclasses","docs":"https://github.com/oxan/djangorestframework-dataclasses/blob/master/README.rst","changelog":"https://github.com/oxan/djangorestframework-dataclasses/blob/master/CHANGELOG.rst","pypi":"https://pypi.org/project/djangorestframework-dataclasses/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","serialization","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-29","next_check":"2026-07-28","install_tag":null}}