Use pydantic with the Django REST framework
Project description
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 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
. The only change is the addition of thedrf_serializer
attribute during class creation (not instance).
Existing Models
If you have an existing code base and you would like to use the drf_serializer
attribute to only specific models, then great news 🥳 - you can easily extend
your existign pydantic
models by adding drf_pydantic.BaseModel
to the list
of parent classes.
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
⚠️ ATTENTION
Inheritance order is important:drf_pydantic.BaseModel
must always go before thepydantic.BaseModel
class.
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
Roadmap
- Add
ENUM
support - Add option to create custom serializer for complex models
- Add support for constraints (max, min, regex, etc.)
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.4.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | bb589ba1a881b655d2940e8499b9d0b4db7477843d4311e0f937e188ffca0845 |
|
MD5 | 080f657d120b784b2bdd760e750f37a9 |
|
BLAKE2b-256 | 0fe6d7433c2a8818be0a09ff6a92fa27831fb397e5f911b959d36dc5c5016154 |