Django Pydantic Field

0.5.4 · active · verified Sat Apr 11

django-pydantic-field integrates Pydantic models with Django's JSONField, offering a type-safe and validated way to store complex data. It provides transparent support for both Pydantic v1 and v2, integrates with Django Forms and Django REST Framework, and enhances static type checking within Django projects. Currently at version 0.5.4, the library is actively maintained with a regular release cadence, addressing compatibility and bug fixes across Django and Pydantic versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Pydantic model (`Foo`) and use it within a Django model's `SchemaField`. It shows both explicit schema declaration and annotation-based usage, including support for basic Python types and nullable fields.

import pydantic
import typing
from django.db import models
from django_pydantic_field import SchemaField

# Define a Pydantic model
class Foo(pydantic.BaseModel):
    count: int
    slug: str = "default"

# Define a Django model using SchemaField
class MyModel(models.Model):
    # Django-like style (explicit schema)
    bar = SchemaField(Foo, default={"count": 5})

    # Annotation-based style (Pydantic-like)
    foo: Foo = SchemaField()

    # Supports standard Python types and annotations
    items: list[Foo] = SchemaField(default=list)

    # null=True correctly infers typing.Optional[Foo] for type checkers
    optional_foo = SchemaField(Foo, null=True)

# Example usage (Django shell context assumed):
# obj = MyModel.objects.create(bar={'count': 10, 'slug': 'test-slug'}, foo={'count': 20}, items=[{'count': 1}, {'count': 2}])
# print(obj.bar.count) # Access Pydantic model attributes
# print(obj.foo.slug) # 'default'
# obj.bar = Foo(count=15, slug='new-slug') # Assign Pydantic model directly
# obj.save()

view raw JSON →