Django JSONField with Pydantic models as a Schema
Reason this release was yanked:
Forward references support appears to broke migrations. I encourage you to downgrade the package unless.
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 datetime import date
from uuid import UUID
from django.db import models
from django_pydantic_field import SchemaField
class Foo(pydantic.BaseModel):
count: int
size: float = 1.0
class Bar(pydantic.BaseModel):
slug: str = "foo_bar"
class MyModel(models.Model):
# Infer schema from field annotation
foo_field: Foo = SchemaField()
# or explicitly pass schema to the field
bar_list: typing.Sequence[Bar] = SchemaField(schema=list[Bar])
# Pydantic exportable types are supported
raw_date_map: dict[int, date] = SchemaField()
raw_uids: set[UUID] = SchemaField()
...
model = MyModel(
foo_field={"count": "5"},
bar_list=[{}],
raw_date_map={1: "1970-01-01"},
raw_uids={"17a25db0-27a4-11ed-904a-5ffb17f92734"}
)
model.save()
assert model.foo_field == Foo(count=5, size=1.0)
assert model.bar_list == [Bar(slug="foo_bar")]
assert model.raw_date_map = {1: date(1970, 1, 1)}
assert model.raw_uids = {UUID("17a25db0-27a4-11ed-904a-5ffb17f92734")}
Practically, schema could be of any type supported by Pydantic.
In addition, an external config
class can be passed for such schemes.
It is possible to define deferred type annotations with string literals. In this case, field schema resolution will be postponed until first model intance:
# models.py
class FooModel(models.Model):
field: "FooSchema" = SchemaField()
class FooSchema(pydantic.BaseModel):
...
...
# logic.py
model = FooModel(field={}) # <<- "FooSchema" reference now resolved to actual schema class
Django REST Framework support
from rest_framework import generics, serializers
from django_pydantic_field.rest_framework import SchemaField, AutoSchema
class MyModelSerializer(serializers.ModelSerializer):
foo_field = SchemaField(schema=Foo)
class Meta:
model = MyModel
fields = '__all__'
class SampleView(generics.RetrieveAPIView):
serializer_class = MyModelSerializer
# optional support of OpenAPI schema generation for Pydantic fields
schema = AutoSchema()
Global approach with typed parser
and renderer
classes
from rest_framework import views
from rest_framework.decorators import api_view, parser_classes, renderer_classes
from django_pydantic_field.rest_framework import SchemaRenderer, SchemaParser, AutoSchema
@api_view(["POST"])
@parser_classes([SchemaParser[Foo]]):
@renderer_classes([SchemaRenderer[list[Foo]]])
def foo_view(request):
assert isinstance(request.data, Foo)
count = request.data.count + 1
return Response([Foo(count=count)])
class FooClassBasedView(views.APIView):
parser_classes = [SchemaParser[Foo]]
renderer_classes = [SchemaRenderer[list[Foo]]]
# optional support of OpenAPI schema generation for Pydantic parsers/renderers
schema = AutoSchema()
def get(self, request, *args, **kwargs):
assert isinstance(request.data, Foo)
return Response([request.data])
def put(self, request, *args, **kwargs):
assert isinstance(request.data, Foo)
count = request.data.count + 1
return Response([request.data])
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
Hashes for django-pydantic-field-0.1.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 81046f72818e2d58d7f6f07d199cf3586bb7dd928c6125bcd77ab7f08106e637 |
|
MD5 | b2cbae9128f333ea64125de9073d838d |
|
BLAKE2b-256 | bd052fbd3f9b0837f0401b26031845879d33ebf7140a828380f9df62b4913017 |
Hashes for django_pydantic_field-0.1.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 381931711a76f12301c7e4462bf734c96e6617429601cae588083c4dce27f138 |
|
MD5 | e8017ac58cc28d4c770aa289837fab6a |
|
BLAKE2b-256 | 887b3d4bd64b3f1fe1f0914f3f22bab640040515732963815ad9615d8b1518ac |