Skip to main content

Add your description here

Project description

DRF Pydantic Serializer

Django REST Framework serializers powered by Pydantic models and dataclasses.

Features

  • Auto-generate DRF serializers from Pydantic models and dataclasses
  • Full Pydantic validation - leverage Pydantic's powerful validation engine
  • Type-safe - get IDE autocomplete and type checking
  • OpenAPI schema generation - automatic drf-spectacular integration
  • Nested models & dataclasses - full support for complex structures
  • Generic support - use PydanticModelSerializer[YourModel] syntax

Installation

pip install drf-pydantic-serializer

Or with Poetry:

poetry add drf-pydantic-serializer

Quick Start

Using Pydantic Models

from pydantic import BaseModel, Field
from drf_pydantic_serializer.serializers import PydanticModelSerializer

class Person(BaseModel):
    name: str
    age: int
    email: str | None = None

# Option 1: Generic syntax
class PersonSerializer(PydanticModelSerializer[Person]):
    pass

# Option 2: Meta class
class PersonSerializer(PydanticModelSerializer):
    class Meta:
        base_model = Person

Using Pydantic Dataclasses

from pydantic.dataclasses import dataclass
from drf_pydantic_serializer.serializers import PydanticDataclassSerializer

@dataclass
class Product:
    id: int
    title: str
    price: float
    description: str | None = None

class ProductSerializer(PydanticDataclassSerializer):
    class Meta:
        pydantic_dataclass = Product

Use in Django Views

from rest_framework.views import APIView
from rest_framework.response import Response

class PersonView(APIView):
    def post(self, request):
        serializer = PersonSerializer(data=request.data)
        if serializer.is_valid():
            person = serializer.save()  # Returns Pydantic model instance
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

Advanced Usage

Nested Models

from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    country: str

class User(BaseModel):
    name: str
    email: str
    address: Address

class UserSerializer(PydanticModelSerializer[User]):
    pass

Lists and Collections

from pydantic import BaseModel

class Tag(BaseModel):
    name: str
    color: str

class Article(BaseModel):
    title: str
    tags: list[Tag]

class ArticleSerializer(PydanticModelSerializer[Article]):
    pass

Validation Errors

Pydantic validation errors are automatically converted to DRF-compatible error format:

serializer = PersonSerializer(data={"name": "John", "age": "invalid"})
serializer.is_valid()  # False
print(serializer.errors)
# {'age': ['Input should be a valid integer...']}

OpenAPI/Swagger Integration

Automatically generate OpenAPI schemas with drf-spectacular:

Setup

pip install drf-spectacular

settings.py:

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'drf_spectacular',
    'drf_pydantic_serializer',  # Auto-registers OpenAPI extension
]

REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

SPECTACULAR_SETTINGS = {
    'TITLE': 'Your API',
    'VERSION': '1.0.0',
}

urls.py:

from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView

urlpatterns = [
    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema')),
]

Now all your Pydantic-based serializers will automatically appear in Swagger UI with proper schema generation!

How It Works

  1. Field Generation: Automatically creates DRF fields from Pydantic model/dataclass fields
  2. Validation: Uses Pydantic's validation during is_valid()
  3. Serialization: Converts instances to JSON-compatible dicts using Pydantic's model_dump()
  4. Deserialization: Creates Pydantic instances from validated data

Comparison with Standard DRF Serializers

Standard DRF:

class PersonSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.IntegerField()
    email = serializers.EmailField(required=False, allow_null=True)

    def validate_age(self, value):
        if value < 0:
            raise ValidationError("Age must be positive")
        return value

With drf-pydantic-serializer:

from pydantic import BaseModel, Field

class Person(BaseModel):
    name: str
    age: int = Field(gt=0)
    email: str | None = None

class PersonSerializer(PydanticModelSerializer[Person]):
    pass

Benefits:

  • Less boilerplate
  • Reuse Pydantic models across your codebase
  • Type safety and IDE support
  • Consistent validation logic

API Reference

PydanticModelSerializer

Serializer for Pydantic BaseModel classes.

Configuration:

  • Generic: PydanticModelSerializer[YourModel]
  • Meta: class Meta: base_model = YourModel
  • Instance: PydanticModelSerializer(pydantic_model=YourModel)

Methods:

  • validate(attrs): Returns validated Pydantic model instance
  • create(validated_data): Returns the Pydantic model instance
  • update(instance, validated_data): Merges and returns updated instance
  • to_representation(instance): Converts to JSON-compatible dict

PydanticDataclassSerializer

Serializer for Pydantic dataclasses.

Configuration:

  • Meta: class Meta: pydantic_dataclass = YourDataclass
  • Instance: PydanticDataclassSerializer(pydantic_dataclass=YourDataclass)

Methods: Same as PydanticModelSerializer

Requirements

  • Python 3.10+
  • Django 4.0+
  • Django REST Framework 3.14+
  • Pydantic 2.0+

License

MIT

Contributing

Contributions welcome! Please open an issue or submit a PR.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf_pydantic_serializer-0.1.0.tar.gz (34.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_pydantic_serializer-0.1.0-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file drf_pydantic_serializer-0.1.0.tar.gz.

File metadata

  • Download URL: drf_pydantic_serializer-0.1.0.tar.gz
  • Upload date:
  • Size: 34.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for drf_pydantic_serializer-0.1.0.tar.gz
Algorithm Hash digest
SHA256 16ae62d4435b4b454c4ff0d262a80c8b1ea9ed6700be518f8ebccc094b300f26
MD5 70e771154858200385450ffcfc9b4722
BLAKE2b-256 cb86d8edb2000a7c851e6db0aa578058ebb3826e65827652ea0371c1af6fc38c

See more details on using hashes here.

Provenance

The following attestation bundles were made for drf_pydantic_serializer-0.1.0.tar.gz:

Publisher: python-publish.yml on BaronVonSario/drf-pydantic-serializer

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file drf_pydantic_serializer-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for drf_pydantic_serializer-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9a702867e256b508a42f251a10a9de3501dbd1a06be23423d9b2ca4cda1804aa
MD5 3341daeed4a21c491412bda276657889
BLAKE2b-256 9bbfe016c54a6cf2ee7f6f51f66ad907b772cbde5079cab52e8d6d0ec615e6d5

See more details on using hashes here.

Provenance

The following attestation bundles were made for drf_pydantic_serializer-0.1.0-py3-none-any.whl:

Publisher: python-publish.yml on BaronVonSario/drf-pydantic-serializer

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page