Skip to content

Commit

Permalink
Merge pull request #26 from surenkov/24-get-config-compatibility
Browse files Browse the repository at this point in the history
Add backward support for pydantic 1.9.*
  • Loading branch information
surenkov authored Jul 24, 2023
2 parents 040d19c + 4d6a9d9 commit 618c439
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 14 deletions.
19 changes: 6 additions & 13 deletions django_pydantic_field/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

import pydantic
from django.core.serializers.json import DjangoJSONEncoder
from pydantic.config import get_config, inherit_config
from pydantic.json import pydantic_encoder
from pydantic.typing import display_as_type

from .utils import get_local_namespace
from .utils import get_local_namespace, inherit_configs

__all__ = (
"SchemaEncoder",
Expand Down Expand Up @@ -134,15 +133,9 @@ def _get_field_schema_name(schema) -> str:

def _get_field_schema_params(schema, config=None, allow_null=False, **kwargs) -> dict:
root_model = t.Optional[schema] if allow_null else schema
params: t.Dict[str, t.Any] = dict(kwargs, __root__=(root_model, ...))
parent_config = getattr(schema, "Config", None)

if config is not None:
config = get_config(config)
if parent_config is not None:
config = inherit_config(config, parent_config)
else:
config = parent_config

params["__config__"] = config
params: t.Dict[str, t.Any] = dict(
kwargs,
__root__=(root_model, ...),
__config__=inherit_configs(schema, config),
)
return params
16 changes: 16 additions & 0 deletions django_pydantic_field/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from __future__ import annotations

import sys
import typing as t

from pydantic.config import BaseConfig, inherit_config

if t.TYPE_CHECKING:
from pydantic import BaseModel


def get_annotated_type(obj, field, default=None) -> t.Any:
try:
Expand All @@ -20,3 +27,12 @@ def get_local_namespace(cls) -> t.Dict[str, t.Any]:
return vars(sys.modules[module])
except (KeyError, AttributeError):
return {}


def inherit_configs(parent: t.Type[BaseModel], config: t.Type | dict | None = None) -> t.Type[BaseConfig]:
parent_config = t.cast(t.Type[BaseConfig], getattr(parent, "Config", BaseConfig))
if config is None:
return parent_config
if isinstance(config, dict):
config = type("Config", (BaseConfig,), config)
return inherit_config(config, parent_config)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "django-pydantic-field"
version = "0.2.7"
version = "0.2.8"
description = "Django JSONField with Pydantic models as a Schema"
readme = "README.md"
license = { file = "LICENSE" }
Expand Down

0 comments on commit 618c439

Please sign in to comment.