Use pydantic with the Django REST framework
Project description
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_pydantic
are fully idenditcal to those created bypydantic
and only thedrf_serializer
attribute 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.BaseModel
must always go before thepydantic.BaseModel
class.
Roadmap
- Add
ENUM
support - Add option to create custom serializer for complex models
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for drf_pydantic-0.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f9f5b9f1a6c98500b13d2ffb76d8c5cf429bde17643b54a48e95e02e5b154a01 |
|
MD5 | abb1c61f09c3d67cc014d93859128bdb |
|
BLAKE2b-256 | 3995a3740b467356f59ee306cfc73d051678d37b6086ebe7fd46cca59ca9e504 |