You can define SchemaField in two ways:
- Django-like style: Pass the schema class as the first argument.
- Annotation-based style: Use Python type annotations (Pydantic-like).
Data assigned to these fields is automatically parsed into Pydantic model instances. The field supports standard Python types, list[T], and null=True (which correctly infers Optional[T] for type checkers).
import pydantic
from django.db import models
from django_pydantic_field import SchemaField
class Foo(pydantic.BaseModel):
count: int
slug: str = "default"
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 t.Optional[Foo] for type checkers
optional_foo = SchemaField(Foo, null=True, default=None)
model = MyModel(foo={"count": 42})
model.save()
# Data is automatically parsed into Pydantic models
assert isinstance(model.foo, Foo)
assert model.foo.count == 42