Skip to content

to_pydantic

django_spire.core.converters.to_pydantic

DjangoToPydanticFieldConverter

Source code in django_spire/core/converters/to_pydantic.py
def __init__(self, model_field: models.Field):
    self.model_field = model_field
    self.kwargs = {}

    self._build_metadata()
    self.field_type = self._get_pydantic_type()
    self._wrap_nullable()

model_field = model_field instance-attribute

kwargs = {} instance-attribute

field_type = self._get_pydantic_type() instance-attribute

field_handlers property

bool_to_json_schema staticmethod

Source code in django_spire/core/converters/to_pydantic.py
@staticmethod
def bool_to_json_schema(value: bool):
    if value:
        return "true"
    else:
        return "false"

build_field

Build and return the Pydantic field type and Field object.

Source code in django_spire/core/converters/to_pydantic.py
def build_field(self) -> Tuple[Type, Any]:
    """Build and return the Pydantic field type and Field object."""
    return self.field_type, Field(**self.kwargs)

django_to_pydantic_model

Source code in django_spire/core/converters/to_pydantic.py
def django_to_pydantic_model(
        model_class: Type[models.Model],
        base_class: Type | None = None,
        include_fields: str | list| tuple | None = None,
        exclude_fields: str | list | tuple | None = None
):
    if not issubclass(model_class, models.Model):
        raise ValueError("model_class must be a subclass of django.db.models.Model")

    if include_fields is None:
        include_fields = []

    if exclude_fields is None:
        exclude_fields = []

    pydantic_fields = {}

    for model_field in model_class._meta.fields:
        field_name = model_field.attname

        if len(include_fields) > 0 and field_name not in include_fields:
            continue

        if len(exclude_fields) > 0 and field_name in exclude_fields:
            continue

        converter = DjangoToPydanticFieldConverter(model_field)
        pydantic_fields[field_name] = converter.build_field()

    return create_model(
        f'{model_class.__name__}',
        __base__=base_class,
        **pydantic_fields
    )