pined-django-pydantic-field
The model field of pined-django.
Pydantic models in the database: a field that gives back validated instances — and writes its own data migrations when the model changes shape.
Installation
pip install pined-django-pydantic-field
Besides Django, the package pulls in pydantic, json-schema-to-pydantic, pined-django-autodetector for the app that writes the migrations, and pined-django-utils for the JSON encoder. The two settings the field needs are under PydanticField.
Works on Python 3.12+ and Django 5.2+.
What's inside
PydanticField
A JSONField that reads and writes validated
Pydantic model instances instead of dicts:
import pydantic
from django.db import models
from pined.django.db.models import PydanticField
class EmailSettings(pydantic.BaseModel):
host: str = "localhost"
port: int = 25
use_tls: bool = True
class Options(models.Model):
email = PydanticField(EmailSettings)
options = Options.objects.first()
options.email.port # 25, an int, on an EmailSettings instance
options.email = {"host": "smtp.example.com", "port": 587} # validated on the way in
options.save()
The field needs two things in the settings: the "pined.django.autodetector"
app, and the field's migration generator registered for it:
INSTALLED_APPS = [..., "pined.django.autodetector"]
PINED = {
"MIGRATION_GENERATORS": {
"pined.django.db.models.PydanticField": "pined.django.db.pydantic_field.migrations.PydanticFieldGenerator",
},
}
Without either, a changed model gets no migration. manage.py check reports
each one missing: the app as pined.django.E006, the generator as
pined.autodetector.E001.
Then change the model, and makemigrations writes the data migration for you:
class EmailSettings(pydantic.BaseModel):
host: str = "localhost"
port: int = 25
use_tls: bool = True
timeout: float = 10.0 # new
$ python manage.py makemigrations myapp
Migrations for 'myapp':
myapp/migrations/0002_revalidate_options_email.py
~ Revalidate data in options.email
# myapp/migrations/0002_revalidate_options_email.py — generated
operations = [
pined.django.db.migrations.AlterPydantic(
model_name="options",
name="email",
schema_hash="9c6d8bf79fa52b7a",
previous_schema_hash="aa233cc7fafb703b",
),
]
Every stored row is re-read, given the new field, and revalidated. Rolling the
migration back does the same in reverse. The schemas are written into the
migrations directory, since they are part of the migration — commit them with
it.
Rows are validated with your model itself while it still has the schema being migrated to. Any other version is one the code no longer has, and is rebuilt from its recorded schema. A table with no values is left alone, and nothing is rebuilt for it.
One shape of Pydantic model does not survive that round trip, and manage.py check says so rather than letting a migration find out:
$ python manage.py check
myapp.Options.email: (pined.django.E001) Pydantic field 'EmailSettings.host' has an alias.
A value is dumped by field name while the recorded schema names that same field
by its alias, so data and schema disagree. The check looks through nested models
and type aliases as well. Where an alias is unavoidable, a plain JSONField
still takes the data.
Usage
pined.django.db.models
PydanticField(model, verbose_name=None, name=None, encoder=None, decoder=None, default=..., **kwargs)
Everything a JSONField takes, plus the Pydantic model as the first argument.
encoder defaults to pined.django.serializers.json.JSONEncoder.
Declared without a default, the field tries to instantiate model with no
arguments. Where every field of the model has a default of its own that
succeeds, and model becomes the field's default factory. Otherwise the field
is left without a default, exactly as a bare JSONField would be.
model is checked at manage.py check time: an aliased field anywhere in it
raises pined.django.E001. A project with any PydanticField and without
"pined.django.autodetector" in INSTALLED_APPS gets pined.django.E006,
once for the whole project.
pined.django.db.migrations
Django's own makemigrations notices a Pydantic model changing shape and
writes AlterPydantic, once "pined.django.autodetector" is in
INSTALLED_APPS. That is the migration generator registered for
PydanticField in PINED["MIGRATION_GENERATORS"] at work — see
pined-django-autodetector.
A field or model renamed in the same run keeps its schema history: the operation
migrates from the schema the rows hold, under the new name.
Each app's schema versions are kept in one _pydantic_schemas.json beside its
migrations, keyed by hash. It is how an old shape and a new one can both be
reconstructed later, so commit it along with the migration. The hash alone says
which shape it stands for, so renaming a field or a model moves nothing in the
file. The _schema_<model>__<field>.json files that earlier releases wrote are
still read; the next schema saved carries their content into the app's file,
after which they can be deleted.
A "change of shape" is whatever changes what the model accepts: fields added,
removed or retyped, defaults, constraints, aliases, extra. Renaming the model,
rewriting its docstring, documenting a field, reordering the field declarations
or the members of a Literal — none of those count, and none of them will
rewrite a table.
AlterPydantic(
model_name, # the django model, e.g. "options"
name, # the PydanticField on it, e.g. "email"
schema_hash, # the schema being migrated to
previous_schema_hash=None, # left out when the field is new
forwards_defaults=None,
backwards_defaults=None,
forwards_transform=None,
backwards_transform=None,
override_fields=None,
)
forwards_defaults and backwards_defaults backfill values. Alongside plain
values they take three helpers, which resolve in the order F, R, P — so
P can read what the other two just produced. F copies from another Django
model field, R renames a field of the Pydantic model, and P is F for the
Pydantic model:
| Helper | Takes the value from |
|---|---|
F("field") |
another field of the Django model; a dotted path reaches inside a nested PydanticField or JSONField |
R("old_name") |
the Pydantic field it is renaming, value untouched |
P("field") |
another field of the same Pydantic model |
from pined.django.db.migrations import AlterPydantic, F, P, R
AlterPydantic(
model_name="terminal",
name="metadata",
schema_hash="3a14deee5c255329",
forwards_defaults={
"current_software_version": F("current_software_version"),
"android_version": R("os_version"),
"also_version": P("android_version"),
"update_attempts": F("extra.software.update_attempts"),
},
)
A backfilled value lands only where the row has none or still holds the Pydantic
default. To overwrite regardless, name the field in override_fields, or pass
"*" for all of them — but take care: this replaces data your users
entered. On a field being created for the first time, forwards_defaults
always wins over the model's own defaults.
For what defaults can't express — dropping a field, computing one from several —
forwards_transform and backwards_transform take a function over the raw JSON
value. They run last.
from pined.django.db.migrations import AlterPydantic, P
def drop_legacy_version(data: dict[str, Any]) -> dict[str, Any]:
data.pop("current_software_version", None)
return data
AlterPydantic(
model_name="terminal",
name="metadata",
schema_hash="92ce2171086e292a",
previous_schema_hash="3a14deee5c255329",
forwards_defaults={
"software_version": P("current_software_version"),
},
forwards_transform=drop_legacy_version,
)
A row whose column holds SQL NULL is passed over. NULL says the field has no
value, not that it holds an empty one, so neither the defaults nor
override_fields="*" nor a transform is offered such a row — putting a document
there is a decision about data rather than about schema. Write a RunPython
ahead of the operation where that is what you mean.
License
MIT. See LICENSE.
Metadata
Release files for pined-django-pydantic-field 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pined_django_pydantic_field-0.3.0.tar.gz | 27.7 kB | With provenance | Details for pined_django_pydantic_field-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pined_django_pydantic_field-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for pined_django_pydantic_field-0.3.0-py3-none-any.whl |
Total release size: 58.2 kB
Release files / pined_django_pydantic_field-0.3.0.tar.gz
| Download URL | pined_django_pydantic_field-0.3.0.tar.gz |
|---|---|
| Size | 27.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7423a2842899bea149878371601188df8db627fe7b3fa65806727c9be4ef85fb
|
|
BLAKE2b-256 checksum How to use checksums |
4e5734d7853bf77e2a95835155177ec32af83913e1da5bfe20ad8d7a1d584943
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logRelease files / pined_django_pydantic_field-0.3.0-py3-none-any.whl
| Download URL | pined_django_pydantic_field-0.3.0-py3-none-any.whl |
|---|---|
| Size | 30.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
40af7cdd60ff74215c1392bf49dbcc98b043bc09a82763b57153fc43ddfc7b03
|
|
BLAKE2b-256 checksum How to use checksums |
5f7f1621b3c67a38abf57932a9ebda2513e3883aa9bb991bd3fa1116b37b6ad7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logSecurity for pined-django-pydantic-field 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pined_django_pydantic_field-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.