Django JSONField with Pydantic models as a Schema
Project description
Django + Pydantic = 🖤
Django JSONField with Pydantic models as a Schema
Usage
Install the package with pip install django-pydantic-field
.
import pydantic
from django.db import models
from django_pydantic_field import PydanticSchemaField
class Foo(pydantic.BaseModel):
count: int
size: float = 1.0
class Bar(pydantic.BaseModel):
slug: str = "foo_bar"
class MyModel(models.Model):
foo_field = PydanticSchemaField(schema=Foo)
bar_list = PydanticSchemaField(schema=list[Bar])
...
model = MyModel(foo_field={"count": "5"}, bar_list=[{}])
model.save()
assert model.foo_field == Foo(count=5, size=1.0)
assert model.bar_list == [Bar(slug="foo_bar")]
Django REST Framework support
from rest_framework import serializers
from django_pydantic_field.rest_framework import PydanticSchemaField
class MyModelSerializer(serializers.ModelSerializer):
foo_field = PydanticSchemaField(schema=Foo)
class Meta:
model = MyModel
fields = '__all__'
Global approach with typed parser
and renderer
classes
from rest_framework.decorators import api_view, parser_classes, renderer_classes
from django_pydantic_field.rest_framework import PydanticSchemaRenderer, PydanticSchemaParser
@api_view(["POST"])
@parser_classes([PydanticSchemaParser[Foo]]):
@renderer_classes([PydanticSchemaRenderer[list[Foo]]])
def foo_view(request):
assert isinstance(request.data, Foo)
count = request.data.count + 1
return Response([Foo(count=count)])
Acknowledgement
- Churkin Oleg for his Gist as a source of inspiration;
- Boutique Air Flight Operations platform as a test ground;
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
Close
Hashes for django-pydantic-field-0.0.4.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8abeae3b707064180fd60fa82ed6ddc28f42379d89f3a15c0e4e70621606483f |
|
MD5 | 1aec12bc39093ab7aea1dcf5f87a7a8f |
|
BLAKE2b-256 | 96cde1d43eefd6a227bed8ba96760a4445d406e6d116c494bd2a1f163c793110 |
Close
Hashes for django_pydantic_field-0.0.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fa266767a7dd3df5a42dedfd106eb2c93001e597a8ad39be37e0ae060d893281 |
|
MD5 | eae53651f302070f1d0c52320d3c223b |
|
BLAKE2b-256 | 66d8e7c9eb8b917099d15d6a84754ef111093e321a21a8a37f258862fd3eba51 |