Use pydantic with Django REST framework
Introduction
Pydantic is a Python library used to perform data serialization and validation.
Django REST framework is a framework built on top of Django used to write REST APIs.
If you develop DRF APIs and rely on pydantic for data validation/(de)serialization,
then drf-pydantic is for you :heart_eyes:.
[!NOTE] The latest version of
drf_pydanticonly supportspydanticv2. Support forpydanticv1 is available in the1.*version.
Performance
Translation between pydantic models and DRF serializers is done during class
creation (e.g., when you first import the model). This means that there will be
zero runtime impact when using drf_pydantic while your application is running.
Installation
pip install drf-pydantic
Usage
General
Use drf_pydantic.BaseModel instead of pydantic.BaseModel when creating your
models:
from drf_pydantic import BaseModel
class MyModel(BaseModel):
name: str
addresses: list[str]
MyModel.drf_serializer would be equvalent to the following DRF Serializer class:
class MyModelSerializer:
name = CharField(allow_null=False, required=True)
addresses = ListField(
allow_empty=True,
allow_null=False,
child=CharField(allow_null=False),
required=True,
)
Whenever you need a DRF serializer you can get it from the model like this:
my_value = MyModel.drf_serializer(data={"name": "Van", addresses: ["Gym"]})
my_value.is_valid(raise_exception=True)
[!NOTE] Models created using
drf_pydanticare fully idenditcal to those created bypydantic. The only change is the addition of thedrf_serializerattribute.
Pydantic Validation
By default the generated serializer only uses DRF's validation; however, pydantic
models are often more complex and their numerous validation rules cannot be
translated to DRF. To enable pydantic validators to be run whenever the serializer
validates some data, set the validate_pydantic parameter
within drf_config property of your model to True:
from drf_pydantic import BaseModel
class MyModel(BaseModel):
name: str
addresses: list[str]
drf_config = {"validate_pydantic": True}
With this option enabled, any time you perform validation on your serializer
(e.g., using .is_valid) its parent pydantic model will be validated too and its
exception will be wrapped within the DRF's ValidationError. This makes your complext
pydantic validation logic fully compatible with DRF views.
If you want to raise the pydantic's ValidationError directly, you should
set validation_error to pydantic:
from drf_pydantic import BaseModel
class MyModel(BaseModel):
name: str
addresses: list[str]
drf_config = {"validate_pydantic": True, "validation_error": "pydantic"}
[!WARNING] When a model would be invalid from both DRF's and pydantic's perspectives, a DRF value will be raised regardless of what
validation_erroris set to because DRF validation always runs first.
[!CAUTION] Setting
validation_errortopydanticwill break DRF views because they will no longer be able to intelligently handle DRF'sValidationError.
Existing Models
If you have an existing code base and you would like to add the drf_serializer
attribute only to some of your models, then I have great news - you can easily
extend your existing pydantic models by adding drf_pydantic.BaseModel to the list
of parent classes of the model you want to extend.
Your existing pydantic models:
from pydantic import BaseModel
class Pet(BaseModel):
name: str
class Dog(Pet):
breed: str
Update your Dog model and get serializer via the drf_serializer:
from drf_pydantic import BaseModel as DRFBaseModel
from pydantic import BaseModel
class Pet(BaseModel):
name: str
class Dog(DRFBaseModel, Pet):
breed: str
Dog.drf_serializer
[!IMPORTANT] Inheritance order is important:
drf_pydantic.BaseModelmust always go before thepydantic.BaseModelclass.
Nested Models
If you have nested models and you want to generate serializer only from one of them,
you don't have to update all models - only update the model you need, drf_pydantic
will generate serializers for all normal nested pydantic models for free!
from drf_pydantic import BaseModel as DRFBaseModel
from pydantic import BaseModel
class Apartment(BaseModel):
floor: int
tenant: str
class Building(BaseModel):
address: str
aparments: list[Apartment]
class Block(DRFBaseModel):
buildings: list[Buildind]
Block.drf_serializer
Manual Serializer Configuration
If drf_pydantic does not generate the serializer you need, you can either granularly
configure which DRF serializer fields to use for each pydantic field, or you can
create a custom serializer for the model altogether.
[!IMPORTANT] When manually configuring the serializer you are responsible for setting all properties of the fields (e.g.,
allow_null,required,default, etc.).drf_pydanticdoes not perform any introspection for fields that are manually configured or for any fields if a custom serializer is used.
Per-Field Configuration
from typing import Annotated
from drf_pydantic import BaseModel
from rest_framework.serializers import IntegerField
class Person(BaseModel):
name: str
age: Annotated[float, IntegerField(min_value=0, max_value=100)]
Custom Serializer
In example below, Person will use MyCustomSerializer as its drf serializer.
Employee will have its own serializer generated by drf_pydantic because it
does not have a user-defined drf_serializer attribute (it's never inherited).
Company will have its own serializer generated by drf_pydantic and it will use
Person's manually-defined serializer for its ceo field.
from drf_pydantic import BaseModel
from rest_framework.serializers import Serializer
class MyCustomSerializer(Serializer):
name = CharField(allow_null=False, required=True)
age = IntegerField(allow_null=False, required=True)
class Person(BaseModel):
name: str
age: float
drf_serializer = MyCustomSerializer
class Employee(Person):
salary: float
class Company(BaseModel):
ceo: Person
Additional Properties
Additional field properties are set according
to the following mapping (pydantic -> drf):
description->help_texttitle->labelStringConstraints->min_lengthandmax_lengthattributes are setpattern-> uses special serializer fieldRegexFieldmax_digitsanddecimal_placesattributes are carried over as is (used forDecimaltype). By default uses current decimal context precision.ge/gt->min_valuele/lt->max_value
Metadata
Release files for drf-pydantic 2.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| drf_pydantic-2.6.0.tar.gz | 10.6 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| drf_pydantic-2.6.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 22.6 kB
Release files / drf_pydantic-2.6.0.tar.gz
| Download URL | drf_pydantic-2.6.0.tar.gz |
|---|---|
| Size | 10.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a4a2eb74728871137974bd041938f681de2a884b855069ba8d3858f4d4cd52fa
|
|
BLAKE2b-256 checksum How to use checksums |
d802f433dea0f697b8617ac86ba0e69e0c9df12060827dfb0f3a9beed5ed5899
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.6.9
|
Release files / drf_pydantic-2.6.0-py3-none-any.whl
| Download URL | drf_pydantic-2.6.0-py3-none-any.whl |
|---|---|
| Size | 12.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
fb1356ca8e3cf86ce9faaaa4ebd07d69483c287e6a8d7479ce537c75238136dc
|
|
BLAKE2b-256 checksum How to use checksums |
c2861af1baa30b46f0f5af2b4555bf916f09cf597ff6b31eaaab5ea6d65d70a1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.6.9
|