Use pydantic with Django REST framework
Introduction
Pydantic is a great Python library to perform data serialization and validation.
Django REST framework is a framework built on top of Django which allows writing REST APIs.
If like me you develop DRF APIs and you like pydantic , drf-pydantic is for you 😍.
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]
Whenever you need a DRF serializer you can get it from the model like this:
MyModel.drf_serializer
ℹ️ INFO
Models created usingdrf_pydanticare fully idenditcal to those created bypydanticand only thedrf_serializerattribute is added on class creation.
Custom Base Models
You can also use it as a mixin with your existing pydantic models (no need to change your existing code 🥳):
from drf_pydantic import BaseModel as DRFBaseModel
from pydantic import BaseModel
class MyBaseModel(BaseModel):
value: int
class MyModel(DRFBaseModel, MyBaseModel):
name: str
addresses: list[str]
⚠️ ATTENTION
Inheritance order is important:drf_pydantic.BaseModelmust always go before thepydantic.BaseModelclass.
Roadmap
- Add
ENUMsupport - Add option to create custom serializer for complex models
Metadata
Release files for drf-pydantic 0.2.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-0.2.0.tar.gz | 5.7 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| drf_pydantic-0.2.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 11.2 kB
Release files / drf-pydantic-0.2.0.tar.gz
| Download URL | drf-pydantic-0.2.0.tar.gz |
|---|---|
| Size | 5.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a916070be83957e20b2bcd6c1f875ab6b856cbd03e806d989ce06fe64131e86d
|
|
BLAKE2b-256 checksum How to use checksums |
2b78d528c0d063d0a32354e85e094b18481626a2bc5fa8fe5d01dd76a08e6805
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.2.0 CPython/3.9.13 Linux/5.15.0-1017-azure
|
Release files / drf_pydantic-0.2.0-py3-none-any.whl
| Download URL | drf_pydantic-0.2.0-py3-none-any.whl |
|---|---|
| Size | 5.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
06f25f0a797c80825010e3d0c8bb1ca53649f9c09ab818f222eba86c575f8292
|
|
BLAKE2b-256 checksum How to use checksums |
098cdb04b1c13a81c7f1bbd121de28fc82762e96832d17b2348e2a70740502e3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.2.0 CPython/3.9.13 Linux/5.15.0-1017-azure
|