Registry / web-framework / django-pydantic-field

django-pydantic-field

JSON →
library0.5.4pypypi✓ verified 24d ago

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.

pip install django-pydantic-field
INSTALL
IMPORT
SIG · DJANGO-PYDANTIC-FI
D
django-pydantic-field
web-frameworkpythonv0.5.4
Install
5.7s avg
Import
1008ms
Disk
76MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.060s · 76.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 5.7s · import 0.956s · 76MB
76MB installed
● package 76MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SchemaField
from django_pydantic_field import SchemaField
from django_pydantic_field.fields import PydanticSchemaField
Older versions (pre-0.1.0) might have used `PydanticSchemaField` from a sub-module, but `SchemaField` directly from the top-level package is the current and recommended import.

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()
Debug
Known issues
breakingSupport for Python 3.8 and 3.9 was dropped in version 0.4.0. Projects using these Python versions must either upgrade their Python environment or pin `django-pydantic-field` to a version prior to 0.4.0.
fix
Upgrade Python to 3.10 or newer, or downgrade `django-pydantic-field` to `<0.4.0`.
affects: >=0.4.0
breakingPydantic v2 introduces significant breaking changes (e.g., `dict()` to `model_dump()`, `json()` to `model_dump_json()`, `Config` class to `model_config` dict). While `django-pydantic-field` aims for transparent support, direct interaction with Pydantic models in your application code will require migrating to Pydantic v2's API. Pydantic v1 is also incompatible with Python 3.14 and newer, forcing a Pydantic v2 migration if using newer Python versions.
fix
Consult Pydantic's official migration guide for V1 to V2. Use `bump-pydantic` tool for automated code transformation. Leverage `pydantic.v1` namespace if a gradual migration is needed.
affects: All versions supporting Pydantic (implicitly impacts user code depending on Pydantic version)
gotchaSerializing complex Pydantic types (e.g., union types like `list[Model] | None`, Pydantic v2 constrained types like `conint`, `Annotated` types, or nested dataclasses) within Django migrations can lead to infinite recursion or incorrect serialization. This has been a recurring issue fixed across several minor releases.
fix
Ensure you are on the latest `django-pydantic-field` version. For highly complex schemas, review migration files carefully after generation. Test migrations thoroughly in development environments. Consider simplifying schemas or providing custom migration serialization if issues persist.
affects: <0.5.3 (older versions had specific issues, newer versions have fixes but complexity remains a potential source)
gotchaIn Pydantic v1, `Optional[Type]` implicitly defaulted to `None`. In Pydantic v2, `Optional[Type]` (or `Type | None`) means the field is required but can accept `None` as a valid value, not that it has a default of `None`. This can lead to unexpected validation errors if `null=True` is not explicitly set on `SchemaField` or if `default=None` is not provided in Pydantic.
fix
For nullable fields, explicitly set `default=None` in your Pydantic model if it should be optional with a `None` default, and set `null=True` on `SchemaField` in your Django model. For mutable defaults (lists, dicts), always use `default_factory=list` or `default_factory=dict` in Pydantic models to prevent shared mutable state across instances.
affects: All versions (behavior difference between Pydantic v1 and v2)
gotcha`django-pydantic-field` performs validation during Django's `manage.py check` command (e.g., `pydantic.E002: Default value serialization errors`). If your Pydantic schemas or their default values are not correctly serializable, Django's system checks will raise errors.
fix
Ensure all default values for `SchemaField` are JSON serializable. For complex or mutable defaults, use Pydantic's `default_factory` to provide a callable that returns the default value upon instantiation. Run `python manage.py check` regularly to catch these issues early.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pydantic'
The Pydantic library or its core components are not installed, or there's an issue with the Python environment where `django-pydantic-field` is being used.
fix
Install Pydantic using `pip install pydantic` or ensure it's installed in the active virtual environment. For Pydantic v2, ensure `pydantic-core` is also correctly installed, as it's a critical dependency.
ValidationError: ... field required (type=value_error.missing)
Data provided for a `SchemaField` does not contain a value for a Pydantic model field that is marked as required. In Pydantic v2, `Optional[Type]` without a default value is considered a required field that can accept `None`.
fix
Provide a value for the missing field in the input data, or if the field should be truly optional, define it with a default value, e.g., `field_name: Optional[str] = None`.
AttributeError: 'BaseModel' object has no attribute 'dict'
This error typically occurs when code written for Pydantic v1 (which uses `.dict()` or `.json()` for serialization) is run with Pydantic v2. Pydantic v2 renamed these methods to `model_dump()` and `model_dump_json()`.
fix
Update your code to use `my_model_instance.model_dump()` instead of `my_model_instance.dict()` and `my_model_instance.model_dump_json()` instead of `my_model_instance.json()` when working with Pydantic v2 models.
SystemCheckError: pydantic.E001: Schema resolution errors
Django's system checks, integrated by `django-pydantic-field`, identified an issue with the Pydantic schema definition (e.g., unresolvable forward references, incorrect type hints) or a problem with how default values are configured for the `SchemaField`.
fix
Inspect the Pydantic model definition used by your `SchemaField` for any syntax errors, unresolved forward references (e.g., string-based type hints for models not yet defined), or invalid default values that cannot be serialized or validated against the schema. Ensure all referenced models are accessible when the Django app loads.
ImportError: cannot import name 'PydanticField' from 'django_pydantic_field'
The `PydanticField` class is not directly exposed from the top-level `django_pydantic_field` package; it resides within the `pydantic_field` sub-package.
fix
Use the correct import path for `PydanticField` based on your Pydantic version or for auto-detection:
`from pydantic_field import PydanticField` (recommended for versions >= 0.5.0)
Alternatively, for specific Pydantic versions:
`from pydantic_field.v1 import PydanticField`
`from pydantic_field.v2 import PydanticField`
Upgrade
Version history
0.5.4latest on PyPI · released Feb 22, 2026
Audit
Dependencies
DjangorequiredCore framework integration.
PydanticrequiredProvides the schema definition and validation engine. Supports both v1 and v2, but specific Python versions might necessitate Pydantic v2.
Agent activity
13 hits · last 30 days
node
12
Resources
django-pydantic-field — pip install django-pydantic-field · libregistry