{"id":9707,"library":"drf-pydantic","title":"DRF Pydantic Integration","description":"drf-pydantic is a Python library that enables seamless integration of Pydantic models with the Django REST Framework (DRF). It allows developers to use Pydantic for data validation and serialization within DRF serializers, leveraging Pydantic's robust schema definition and validation capabilities. The current version is 2.9.1, and it typically follows a release cadence tied to Django, DRF, or Pydantic updates, with minor releases for features and bug fixes.","status":"active","version":"2.9.1","language":"en","source_language":"en","source_url":"https://github.com/johann-spangenberg/drf-pydantic","tags":["django","drf","pydantic","serialization","validation","rest-api"],"install":[{"cmd":"pip install drf-pydantic","lang":"bash","label":"Install drf-pydantic"}],"dependencies":[{"reason":"Core dependency for Django REST Framework integration.","package":"djangorestframework","optional":false},{"reason":"Core dependency for Pydantic model validation and serialization.","package":"pydantic","optional":false}],"imports":[{"note":"Use this for standard Pydantic BaseModel serialization.","symbol":"PydanticSerializer","correct":"from drf_pydantic.serializers import PydanticSerializer"},{"note":"Use this for Pydantic models derived from Django models (requires django-pydantic).","symbol":"PydanticModelSerializer","correct":"from drf_pydantic.serializers import PydanticModelSerializer"},{"note":"Required to enable schema generation for Pydantic serializers in DRF's schema views (e.g., OpenAPI/Swagger).","symbol":"apply_patch","correct":"from drf_pydantic.patch import apply_patch"}],"quickstart":{"code":"from pydantic import BaseModel, Field\nfrom typing import Optional\nfrom drf_pydantic.serializers import PydanticSerializer\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n# 1. Define your Pydantic model\nclass ItemCreate(BaseModel):\n    name: str = Field(..., max_length=100)\n    description: Optional[str] = None\n    price: float = Field(..., gt=0)\n\n# 2. Create a PydanticSerializer\nclass ItemCreateSerializer(PydanticSerializer):\n    class Meta:\n        model = ItemCreate\n\n# 3. Use the serializer in a DRF View\nclass ItemAPIView(APIView):\n    def post(self, request):\n        serializer = ItemCreateSerializer(data=request.data)\n        serializer.is_valid(raise_exception=True)\n        # Access validated data as a Pydantic model instance\n        item_instance: ItemCreate = serializer.validated_data\n        # In a real application, you would save `item_instance` to a database\n        # or perform other business logic here.\n        print(f\"Received item: {item_instance.dict()}\")\n        return Response(item_instance.dict(), status=status.HTTP_201_CREATED)\n\n    def get(self, request):\n        # Example of serializing a Pydantic instance for output\n        example_item = ItemCreate(name=\"Sample Widget\", price=29.99)\n        serializer = ItemCreateSerializer(instance=example_item)\n        return Response(serializer.data)","lang":"python","description":"This quickstart demonstrates how to define a Pydantic model, create a `PydanticSerializer` for it, and then use it within a DRF `APIView` for both validating incoming data (POST) and serializing outgoing data (GET). The validated data from the serializer is a Pydantic model instance."},"warnings":[{"fix":"Rewrite serializers using `PydanticSerializer` or `PydanticModelSerializer` and their `Meta` classes. Consult the official documentation for v2.x migration.","message":"Version 2.x was a complete rewrite, introducing `PydanticSerializer` and `PydanticModelSerializer` as the primary components. Code written for 1.x (which used `PydanticField` and `PydanticMixin`) is not compatible with 2.x.","severity":"breaking","affected_versions":"<2.0.0"},{"fix":"Ensure you are using the correct serializer for your Pydantic model type. Use `PydanticSerializer` for standalone Pydantic models. Use `PydanticModelSerializer` only when your Pydantic model is designed to map directly to a Django ORM model.","message":"There are two main serializers: `PydanticSerializer` for general Pydantic `BaseModel`s, and `PydanticModelSerializer` for Pydantic models specifically generated from Django models (often using `django-pydantic`). Using `PydanticModelSerializer` with a regular `BaseModel` not derived from a Django model will lead to errors.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always include `class Meta: model = YourPydanticModel` where `YourPydanticModel` is your Pydantic `BaseModel` or Django-derived Pydantic model.","message":"When using `PydanticSerializer` or `PydanticModelSerializer`, you must explicitly define `class Meta: model = YourPydanticModel` within your serializer. Forgetting this or misconfiguring it will prevent the serializer from functioning correctly.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure your `PydanticModelSerializer` class has an inner `Meta` class with `model = YourPydanticModel` pointing to a valid Pydantic model that originated from a Django model.","cause":"Attempting to use `PydanticModelSerializer` without defining the `Meta.model` attribute, or providing an invalid model type.","error":"TypeError: 'PydanticModelSerializer' object has no attribute 'get_serializer_class'"},{"fix":"Inspect the error message for the specific field and validation rule that failed. Adjust the incoming request data to conform to the Pydantic model's requirements. Ensure your Pydantic model is correctly defined.","cause":"Pydantic validation failed because incoming data does not match the schema defined in the Pydantic model (e.g., a required field is missing or has the wrong type).","error":"ValidationError: 1 validation error for ItemCreate\\nname\\n  field required (type=value_error.missing)"},{"fix":"For `PydanticModelSerializer`, ensure `class Meta: model = YourPydanticModel` is set correctly, and that `YourPydanticModel` is indeed a Pydantic model generated from a Django model (e.g., using `django-pydantic`). If using a plain Pydantic model, switch to `PydanticSerializer`.","cause":"This error occurs with `PydanticModelSerializer` if it cannot correctly infer or is not explicitly told which Pydantic model to use, usually when the Pydantic model is not properly derived from a Django model or the `Meta.model` is missing/incorrect.","error":"django.core.exceptions.ImproperlyConfigured: 'PydanticModelSerializer' requires a 'model' attribute to be specified in the 'Meta' class or as a keyword argument."}]}