Metadata-Version: 2.5
Name: pined-django-pydantic-field
Version: 0.3.0
Summary: A Django model field for pydantic models, with the data migrations a change of shape needs
Project-URL: Homepage, https://github.com/pinecrew/pined-django
Project-URL: Repository, https://github.com/pinecrew/pined-django
Project-URL: Issues, https://github.com/pinecrew/pined-django/issues
Project-URL: Changelog, https://github.com/pinecrew/pined-django/blob/main/packages/pydantic-field/CHANGELOG.md
Author-email: citrux <369565@gmail.com>, illaech <illaech@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: data-migrations,django,jsonfield,migrations,model-field,pydantic
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: django>=5.2
Requires-Dist: json-schema-to-pydantic==0.5.0
Requires-Dist: pined-django-autodetector<0.4,>=0.3.0
Requires-Dist: pined-django-utils<0.4,>=0.3.0
Requires-Dist: pydantic>=2.11.4
Description-Content-Type: text/markdown

# pined-django-pydantic-field

*The model field of [pined-django](https://github.com/pinecrew/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

```bash
pip install pined-django-pydantic-field
```

Besides Django, the package pulls in pydantic, json-schema-to-pydantic,
[pined-django-autodetector](https://github.com/pinecrew/pined-django/tree/main/packages/autodetector)
for the app that writes the migrations, and
[pined-django-utils](https://github.com/pinecrew/pined-django/tree/main/packages/utils)
for the JSON encoder. The two settings the field needs are under
[PydanticField](#pydanticfield).

Works on Python 3.12+ and [Django](https://www.djangoproject.com/) 5.2+.

## What's inside

### PydanticField

A `JSONField` that reads and writes validated
[Pydantic](https://docs.pydantic.dev/) model instances instead of dicts:

```python
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)
```

```python
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:

```python
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:

```python
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
```

```python
# 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`

```python
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](https://github.com/pinecrew/pined-django/tree/main/packages/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.

```python
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                                                                |

```python
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.

```python
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](LICENSE).
