diff --git a/test_enum_descriptions.py b/test_enum_descriptions.py new file mode 100644 index 0000000..9b452d1 --- /dev/null +++ b/test_enum_descriptions.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Test script to understand current enum handling and test x-enumDescriptions.""" + +import os + +os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" +import django + +django.setup() + +from django.db import models +from django.utils.translation import gettext_lazy as _ +from tests.utils import get_openapi_schema_from_field + + +class YearInSchool(models.TextChoices): + FRESHMAN = "FR", _("Freshman") + SOPHOMORE = "SO", _("Sophomore") + JUNIOR = "JR", _("Junior") + SENIOR = "SR", _("Senior") + GRADUATE = "GR", _("Graduate") + + +# Test current behavior +field = models.CharField(max_length=2, choices=YearInSchool.choices) +schema = get_openapi_schema_from_field(field) + +print("Current OpenAPI schema:") +import json + +print(json.dumps(schema, indent=2)) diff --git a/test_schema_extra.py b/test_schema_extra.py new file mode 100644 index 0000000..f838f9b --- /dev/null +++ b/test_schema_extra.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Test script to explore how to add custom schema extensions in Pydantic.""" + +import os + +os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" +import django + +django.setup() + +from enum import Enum +from typing import Annotated +from pydantic import BaseModel, Field +from pydantic.json_schema import JsonSchemaValue, GenerateJsonSchema +from pydantic_core import core_schema +import json + + +# Create a test enum with custom schema modifier +class TestEnum(str, Enum): + A = "a" + B = "b" + C = "c" + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: GenerateJsonSchema + ) -> JsonSchemaValue: + """Add custom x-enumDescriptions to the enum schema.""" + json_schema = handler(core_schema) + json_schema["x-enumDescriptions"] = { + "a": "Choice A", + "b": "Choice B", + "c": "Choice C", + } + return json_schema + + +# Test how to add custom schema properties +class TestModel(BaseModel): + enum_field: TestEnum + + +schema = TestModel.model_json_schema() +print("Test schema with custom __get_pydantic_json_schema__:") +print(json.dumps(schema, indent=2)) diff --git a/uv.lock b/uv.lock index e15ad96..c975e8d 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 2 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.13'", @@ -523,7 +523,7 @@ wheels = [ [[package]] name = "django2pydantic" -version = "0.6.0" +version = "0.6.1" source = { editable = "." } dependencies = [ { name = "beartype" },