djangorestframework-dataclasses

1.4.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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)

view raw JSON →