{"id":3971,"library":"django-pydantic-field","title":"Django Pydantic Field","description":"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.","status":"active","version":"0.5.4","language":"en","source_language":"en","source_url":"https://github.com/surenkov/django-pydantic-field","tags":["django","pydantic","jsonfield","type-safe","validation","orm"],"install":[{"cmd":"pip install django-pydantic-field","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core framework integration.","package":"Django"},{"reason":"Provides the schema definition and validation engine. Supports both v1 and v2, but specific Python versions might necessitate Pydantic v2.","package":"Pydantic"}],"imports":[{"note":"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.","wrong":"from django_pydantic_field.fields import PydanticSchemaField","symbol":"SchemaField","correct":"from django_pydantic_field import SchemaField"}],"quickstart":{"code":"import pydantic\nimport typing\nfrom django.db import models\nfrom django_pydantic_field import SchemaField\n\n# Define a Pydantic model\nclass Foo(pydantic.BaseModel):\n    count: int\n    slug: str = \"default\"\n\n# Define a Django model using SchemaField\nclass MyModel(models.Model):\n    # Django-like style (explicit schema)\n    bar = SchemaField(Foo, default={\"count\": 5})\n\n    # Annotation-based style (Pydantic-like)\n    foo: Foo = SchemaField()\n\n    # Supports standard Python types and annotations\n    items: list[Foo] = SchemaField(default=list)\n\n    # null=True correctly infers typing.Optional[Foo] for type checkers\n    optional_foo = SchemaField(Foo, null=True)\n\n# Example usage (Django shell context assumed):\n# obj = MyModel.objects.create(bar={'count': 10, 'slug': 'test-slug'}, foo={'count': 20}, items=[{'count': 1}, {'count': 2}])\n# print(obj.bar.count) # Access Pydantic model attributes\n# print(obj.foo.slug) # 'default'\n# obj.bar = Foo(count=15, slug='new-slug') # Assign Pydantic model directly\n# obj.save()","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade Python to 3.10 or newer, or downgrade `django-pydantic-field` to `<0.4.0`.","message":"Support 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.","severity":"breaking","affected_versions":">=0.4.0"},{"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.","message":"Pydantic 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.","severity":"breaking","affected_versions":"All versions supporting Pydantic (implicitly impacts user code depending on Pydantic version)"},{"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.","message":"Serializing 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.","severity":"gotcha","affected_versions":"<0.5.3 (older versions had specific issues, newer versions have fixes but complexity remains a potential source)"},{"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.","message":"In 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.","severity":"gotcha","affected_versions":"All versions (behavior difference between Pydantic v1 and v2)"},{"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.","message":"`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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}