From 1ed85e42f892a89ed02368150369093a1ad7a303 Mon Sep 17 00:00:00 2001 From: Koudai Aono Date: Fri, 19 Dec 2025 08:23:27 +0000 Subject: [PATCH 1/5] feat: Add --ignore-enum-constraints option to bypass enum generation --- docs/cli-reference/model-customization.md | 2 +- docs/cli-reference/template-customization.md | 2 +- src/datamodel_code_generator/__init__.py | 2 ++ src/datamodel_code_generator/__main__.py | 2 ++ src/datamodel_code_generator/arguments.py | 6 +++++ src/datamodel_code_generator/cli_options.py | 1 + src/datamodel_code_generator/parser/base.py | 2 ++ .../parser/graphql.py | 24 +++++++++++++++++++ .../parser/jsonschema.py | 24 +++++++++++++------ .../parser/openapi.py | 4 +++- 10 files changed, 59 insertions(+), 10 deletions(-) diff --git a/docs/cli-reference/model-customization.md b/docs/cli-reference/model-customization.md index 164dd4110..ef61ec721 100644 --- a/docs/cli-reference/model-customization.md +++ b/docs/cli-reference/model-customization.md @@ -4008,7 +4008,7 @@ The `--target-python-version` flag controls Python version-specific syntax: This affects import statements and type annotation syntax in generated code. -**See also:** [Output Model Types](../what_is_the_difference_between_v1_and_v2.md), [CI/CD Integration](../ci-cd.md), [Python Version Compatibility](../python-version-compatibility.md) +**See also:** [Python Version Compatibility](../python-version-compatibility.md), [CI/CD Integration](../ci-cd.md), [Output Model Types](../what_is_the_difference_between_v1_and_v2.md) !!! tip "Usage" diff --git a/docs/cli-reference/template-customization.md b/docs/cli-reference/template-customization.md index 1796b65bb..62578714a 100644 --- a/docs/cli-reference/template-customization.md +++ b/docs/cli-reference/template-customization.md @@ -2208,7 +2208,7 @@ the generated Python code. Available formatters are: black, isort, ruff, yapf, autopep8, autoflake. Default is [black, isort]. Use this to customize formatting or disable formatters entirely. -**See also:** [CI/CD Integration](../ci-cd.md), [Code Formatting](../formatting.md) +**See also:** [Code Formatting](../formatting.md), [CI/CD Integration](../ci-cd.md) !!! tip "Usage" diff --git a/src/datamodel_code_generator/__init__.py b/src/datamodel_code_generator/__init__.py index 7b3284c56..77072701e 100644 --- a/src/datamodel_code_generator/__init__.py +++ b/src/datamodel_code_generator/__init__.py @@ -417,6 +417,7 @@ def generate( # noqa: PLR0912, PLR0913, PLR0914, PLR0915 shared_module_name: str = DEFAULT_SHARED_MODULE_NAME, encoding: str = "utf-8", enum_field_as_literal: LiteralType | None = None, + ignore_enum_constraints: bool = False, use_one_literal_as_default: bool = False, use_enum_values_in_discriminator: bool = False, set_default_enum_member: bool = False, @@ -663,6 +664,7 @@ def get_header_and_first_line(csv_file: IO[str]) -> dict[str, Any]: enum_field_as_literal=enum_field_as_literal if enum_field_as_literal is not None else (LiteralType.All if output_model_type == DataModelType.TypingTypedDict else None), + ignore_enum_constraints=ignore_enum_constraints, use_one_literal_as_default=use_one_literal_as_default, use_enum_values_in_discriminator=use_enum_values_in_discriminator, set_default_enum_member=True diff --git a/src/datamodel_code_generator/__main__.py b/src/datamodel_code_generator/__main__.py index bad69e60d..23d8e2798 100644 --- a/src/datamodel_code_generator/__main__.py +++ b/src/datamodel_code_generator/__main__.py @@ -405,6 +405,7 @@ def validate_all_exports_collision_strategy(cls, values: dict[str, Any]) -> dict shared_module_name: str = DEFAULT_SHARED_MODULE_NAME encoding: str = DEFAULT_ENCODING enum_field_as_literal: Optional[LiteralType] = None # noqa: UP045 + ignore_enum_constraints: bool = False use_one_literal_as_default: bool = False use_enum_values_in_discriminator: bool = False set_default_enum_member: bool = False @@ -708,6 +709,7 @@ def run_generate_from_config( # noqa: PLR0913, PLR0917 shared_module_name=config.shared_module_name, encoding=config.encoding, enum_field_as_literal=config.enum_field_as_literal, + ignore_enum_constraints=config.ignore_enum_constraints, use_one_literal_as_default=config.use_one_literal_as_default, use_enum_values_in_discriminator=config.use_enum_values_in_discriminator, set_default_enum_member=config.set_default_enum_member, diff --git a/src/datamodel_code_generator/arguments.py b/src/datamodel_code_generator/arguments.py index 4deff87ba..e8e5f8ea6 100644 --- a/src/datamodel_code_generator/arguments.py +++ b/src/datamodel_code_generator/arguments.py @@ -348,6 +348,12 @@ def start_section(self, heading: str | None) -> None: choices=[lt.value for lt in LiteralType], default=None, ) +typing_options.add_argument( + "--ignore-enum-constraints", + help="Ignore enum constraints and use the base type (e.g., str, int) instead of generating Enum classes", + action="store_true", + default=None, +) typing_options.add_argument( "--field-constraints", help="Use field constraints and not con* annotations", diff --git a/src/datamodel_code_generator/cli_options.py b/src/datamodel_code_generator/cli_options.py index f3635a297..597ff5822 100644 --- a/src/datamodel_code_generator/cli_options.py +++ b/src/datamodel_code_generator/cli_options.py @@ -142,6 +142,7 @@ class CLIOptionMeta: "--use-type-alias": CLIOptionMeta(name="--use-type-alias", category=OptionCategory.TYPING), "--strict-types": CLIOptionMeta(name="--strict-types", category=OptionCategory.TYPING), "--enum-field-as-literal": CLIOptionMeta(name="--enum-field-as-literal", category=OptionCategory.TYPING), + "--ignore-enum-constraints": CLIOptionMeta(name="--ignore-enum-constraints", category=OptionCategory.TYPING), "--disable-future-imports": CLIOptionMeta(name="--disable-future-imports", category=OptionCategory.TYPING), "--use-pendulum": CLIOptionMeta(name="--use-pendulum", category=OptionCategory.TYPING), "--output-datetime-class": CLIOptionMeta(name="--output-datetime-class", category=OptionCategory.TYPING), diff --git a/src/datamodel_code_generator/parser/base.py b/src/datamodel_code_generator/parser/base.py index 5ba2791bb..9dafe82fc 100644 --- a/src/datamodel_code_generator/parser/base.py +++ b/src/datamodel_code_generator/parser/base.py @@ -683,6 +683,7 @@ def __init__( # noqa: PLR0913, PLR0915 shared_module_name: str = DEFAULT_SHARED_MODULE_NAME, encoding: str = "utf-8", enum_field_as_literal: LiteralType | None = None, + ignore_enum_constraints: bool = False, set_default_enum_member: bool = False, use_subclass_enum: bool = False, use_specialized_enum: bool = True, @@ -783,6 +784,7 @@ def __init__( # noqa: PLR0913, PLR0915 self.shared_module_name: str = shared_module_name self.encoding: str = encoding self.enum_field_as_literal: LiteralType | None = enum_field_as_literal + self.ignore_enum_constraints: bool = ignore_enum_constraints self.set_default_enum_member: bool = set_default_enum_member self.use_subclass_enum: bool = use_subclass_enum self.use_specialized_enum: bool = use_specialized_enum diff --git a/src/datamodel_code_generator/parser/graphql.py b/src/datamodel_code_generator/parser/graphql.py index b8ca2dec9..b55999d96 100644 --- a/src/datamodel_code_generator/parser/graphql.py +++ b/src/datamodel_code_generator/parser/graphql.py @@ -134,6 +134,7 @@ def __init__( # noqa: PLR0913 shared_module_name: str = DEFAULT_SHARED_MODULE_NAME, encoding: str = "utf-8", enum_field_as_literal: LiteralType | None = None, + ignore_enum_constraints: bool = False, set_default_enum_member: bool = False, use_subclass_enum: bool = False, use_specialized_enum: bool = True, @@ -227,6 +228,7 @@ def __init__( # noqa: PLR0913 shared_module_name=shared_module_name, encoding=encoding, enum_field_as_literal=enum_field_as_literal, + ignore_enum_constraints=ignore_enum_constraints, use_one_literal_as_default=use_one_literal_as_default, use_enum_values_in_discriminator=use_enum_values_in_discriminator, set_default_enum_member=set_default_enum_member, @@ -414,10 +416,32 @@ def should_parse_enum_as_literal(self, obj: graphql.GraphQLEnumType) -> bool: def parse_enum(self, enum_object: graphql.GraphQLEnumType) -> None: """Parse a GraphQL enum type and add it to results.""" + if self.ignore_enum_constraints: + return self.parse_enum_as_str_type(enum_object) if self.should_parse_enum_as_literal(enum_object): return self.parse_enum_as_literal(enum_object) return self.parse_enum_as_enum_class(enum_object) + def parse_enum_as_str_type(self, enum_object: graphql.GraphQLEnumType) -> None: + """Parse enum as a str type alias when ignoring enum constraints.""" + data_type = self.data_type_manager.get_data_type(Types.string) + data_model_type = self._create_data_model( + model_type=self.data_model_root_type, + reference=self.references[enum_object.name], + fields=[ + self.data_model_field_type( + required=True, + data_type=data_type, + ) + ], + custom_base_class=self.base_class, + custom_template_dir=self.custom_template_dir, + extra_template_data=self.extra_template_data, + path=self.current_source_path, + description=enum_object.description, + ) + self.results.append(data_model_type) + def parse_enum_as_literal(self, enum_object: graphql.GraphQLEnumType) -> None: """Parse enum values as a Literal type.""" data_type = self.data_type(literals=list(enum_object.values.keys())) diff --git a/src/datamodel_code_generator/parser/jsonschema.py b/src/datamodel_code_generator/parser/jsonschema.py index 25ba1ed54..7f16f20be 100644 --- a/src/datamodel_code_generator/parser/jsonschema.py +++ b/src/datamodel_code_generator/parser/jsonschema.py @@ -544,6 +544,7 @@ def __init__( # noqa: PLR0913 shared_module_name: str = DEFAULT_SHARED_MODULE_NAME, encoding: str = "utf-8", enum_field_as_literal: LiteralType | None = None, + ignore_enum_constraints: bool = False, use_one_literal_as_default: bool = False, use_enum_values_in_discriminator: bool = False, set_default_enum_member: bool = False, @@ -638,6 +639,7 @@ def __init__( # noqa: PLR0913 shared_module_name=shared_module_name, encoding=encoding, enum_field_as_literal=enum_field_as_literal, + ignore_enum_constraints=ignore_enum_constraints, use_one_literal_as_default=use_one_literal_as_default, use_enum_values_in_discriminator=use_enum_values_in_discriminator, set_default_enum_member=set_default_enum_member, @@ -852,7 +854,15 @@ def _create_synthetic_enum_obj( def is_constraints_field(self, obj: JsonSchemaObject) -> bool: """Check if a field should include constraints.""" return obj.is_array or ( - self.field_constraints and not (obj.ref or obj.anyOf or obj.oneOf or obj.allOf or obj.is_object or obj.enum) + self.field_constraints + and not ( + obj.ref + or obj.anyOf + or obj.oneOf + or obj.allOf + or obj.is_object + or (obj.enum and not self.ignore_enum_constraints) + ) ) def _resolve_field_flag(self, obj: JsonSchemaObject, flag: Literal["readOnly", "writeOnly"]) -> bool: @@ -1500,7 +1510,7 @@ def _schema_signature(self, prop_schema: JsonSchemaObject | bool) -> str | bool: return prop_schema return json.dumps(prop_schema.dict(exclude_unset=True, by_alias=True), sort_keys=True, default=repr) - def _is_root_model_schema(self, obj: JsonSchemaObject) -> bool: # noqa: PLR6301 + def _is_root_model_schema(self, obj: JsonSchemaObject) -> bool: """Check if schema represents a root model (primitive type with constraints). Based on parse_raw_obj() else branch conditions. Returns True when @@ -1516,7 +1526,7 @@ def _is_root_model_schema(self, obj: JsonSchemaObject) -> bool: # noqa: PLR6301 return False if obj.type == "object": return False - return not obj.enum + return not obj.enum or self.ignore_enum_constraints def _handle_allof_root_model_with_constraints( # noqa: PLR0911, PLR0912 self, @@ -2328,7 +2338,7 @@ def parse_item( # noqa: PLR0911, PLR0912 return self.data_type_manager.get_data_type( Types.object, ) - if item.enum: + if item.enum and not self.ignore_enum_constraints: if self.should_parse_enum_as_literal(item): return self.parse_enum_as_literal(item) return self.parse_enum(name, item, get_special_path("enum", path), singular_name=singular_name) @@ -2401,7 +2411,7 @@ def parse_array_fields( data_types.append(self.parse_all_of(name, obj, get_special_path("allOf", path))) elif obj.is_object: data_types.append(self.parse_object(name, obj, get_special_path("object", path))) - if obj.enum: + if obj.enum and not self.ignore_enum_constraints: data_types.append(self.parse_enum(name, obj, get_special_path("enum", path))) return self.data_model_field_type( data_type=self.data_type(data_types=data_types), @@ -2510,7 +2520,7 @@ def parse_root_type( # noqa: PLR0912 data_type = data_types[0] elif obj.patternProperties: data_type = self.parse_pattern_properties(name, obj.patternProperties, path) - elif obj.enum: + elif obj.enum and not self.ignore_enum_constraints: if self.should_parse_enum_as_literal(obj): data_type = self.parse_enum_as_literal(obj) else: # pragma: no cover @@ -3000,7 +3010,7 @@ def parse_obj( # noqa: PLR0912 self.parse_root_type(name, obj, path) elif obj.type == "object": self.parse_object(name, obj, path) - elif obj.enum and not self.should_parse_enum_as_literal(obj): + elif obj.enum and not self.ignore_enum_constraints and not self.should_parse_enum_as_literal(obj): self.parse_enum(name, obj, path) else: self.parse_root_type(name, obj, path) diff --git a/src/datamodel_code_generator/parser/openapi.py b/src/datamodel_code_generator/parser/openapi.py index fa337bc54..4199fe040 100644 --- a/src/datamodel_code_generator/parser/openapi.py +++ b/src/datamodel_code_generator/parser/openapi.py @@ -214,6 +214,7 @@ def __init__( # noqa: PLR0913 shared_module_name: str = DEFAULT_SHARED_MODULE_NAME, encoding: str = "utf-8", enum_field_as_literal: LiteralType | None = None, + ignore_enum_constraints: bool = False, use_one_literal_as_default: bool = False, use_enum_values_in_discriminator: bool = False, set_default_enum_member: bool = False, @@ -311,6 +312,7 @@ def __init__( # noqa: PLR0913 shared_module_name=shared_module_name, encoding=encoding, enum_field_as_literal=enum_field_as_literal, + ignore_enum_constraints=ignore_enum_constraints, use_one_literal_as_default=use_one_literal_as_default, use_enum_values_in_discriminator=use_enum_values_in_discriminator, set_default_enum_member=set_default_enum_member, @@ -520,7 +522,7 @@ def parse_schema( self.parse_object(name, obj, path) elif obj.is_object: data_type = self.parse_object(name, obj, path) - elif obj.enum: # pragma: no cover + elif obj.enum and not self.ignore_enum_constraints: # pragma: no cover data_type = self.parse_enum(name, obj, path) elif obj.ref: # pragma: no cover data_type = self.get_ref_data_type(obj.ref) From ae41e516309ad1bcd0ce35404d42a56795ba9e0e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 19 Dec 2025 08:24:29 +0000 Subject: [PATCH 2/5] docs: update CLI reference documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated by GitHub Actions --- docs/cli-reference/model-customization.md | 2 +- docs/cli-reference/template-customization.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/cli-reference/model-customization.md b/docs/cli-reference/model-customization.md index ef61ec721..164dd4110 100644 --- a/docs/cli-reference/model-customization.md +++ b/docs/cli-reference/model-customization.md @@ -4008,7 +4008,7 @@ The `--target-python-version` flag controls Python version-specific syntax: This affects import statements and type annotation syntax in generated code. -**See also:** [Python Version Compatibility](../python-version-compatibility.md), [CI/CD Integration](../ci-cd.md), [Output Model Types](../what_is_the_difference_between_v1_and_v2.md) +**See also:** [Output Model Types](../what_is_the_difference_between_v1_and_v2.md), [CI/CD Integration](../ci-cd.md), [Python Version Compatibility](../python-version-compatibility.md) !!! tip "Usage" diff --git a/docs/cli-reference/template-customization.md b/docs/cli-reference/template-customization.md index 62578714a..1796b65bb 100644 --- a/docs/cli-reference/template-customization.md +++ b/docs/cli-reference/template-customization.md @@ -2208,7 +2208,7 @@ the generated Python code. Available formatters are: black, isort, ruff, yapf, autopep8, autoflake. Default is [black, isort]. Use this to customize formatting or disable formatters entirely. -**See also:** [Code Formatting](../formatting.md), [CI/CD Integration](../ci-cd.md) +**See also:** [CI/CD Integration](../ci-cd.md), [Code Formatting](../formatting.md) !!! tip "Usage" From c638f8cc453413c9957786316bbf8545fc8a6c67 Mon Sep 17 00:00:00 2001 From: Koudai Aono Date: Fri, 19 Dec 2025 08:47:43 +0000 Subject: [PATCH 3/5] feat: Add test for --ignore-enum-constraints option and generated output --- .../graphql/enums_ignore_enum_constraints.py | 35 +++++++++++++++++++ tests/main/graphql/test_main_graphql.py | 25 +++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tests/data/expected/main/graphql/enums_ignore_enum_constraints.py diff --git a/tests/data/expected/main/graphql/enums_ignore_enum_constraints.py b/tests/data/expected/main/graphql/enums_ignore_enum_constraints.py new file mode 100644 index 000000000..2dc996991 --- /dev/null +++ b/tests/data/expected/main/graphql/enums_ignore_enum_constraints.py @@ -0,0 +1,35 @@ +# generated by datamodel-codegen: +# filename: enums.graphql +# timestamp: 2019-07-26T00:00:00+00:00 + +from __future__ import annotations + +from pydantic import BaseModel +from typing_extensions import TypeAlias + +Boolean: TypeAlias = bool +""" +The `Boolean` scalar type represents `true` or `false`. +""" + + +String: TypeAlias = str +""" +The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. +""" + + +class Color(BaseModel): + __root__: str + + +class EmployeeShiftStatus(BaseModel): + """ + Employee shift status + """ + + __root__: str + + +class EnumWithOneField(BaseModel): + __root__: str diff --git a/tests/main/graphql/test_main_graphql.py b/tests/main/graphql/test_main_graphql.py index bcf2be53d..1f7f8a697 100644 --- a/tests/main/graphql/test_main_graphql.py +++ b/tests/main/graphql/test_main_graphql.py @@ -236,6 +236,31 @@ def test_main_graphql_enums_to_typed_dict(output_file: Path) -> None: ) +@pytest.mark.cli_doc( + options=["--ignore-enum-constraints"], + input_schema="graphql/enums.graphql", + cli_args=["--ignore-enum-constraints"], + golden_output="graphql/enums_ignore_enum_constraints.py", + comparison_output="graphql/enums.py", +) +def test_main_graphql_enums_ignore_enum_constraints(output_file: Path) -> None: + """Ignore enum constraints and use base string type instead of Enum classes. + + The `--ignore-enum-constraints` flag ignores enum constraints and uses + the base type (str) instead of generating Enum classes. This is useful + when you need flexibility in the values a field can accept beyond the + defined enum members. + """ + run_main_and_assert( + input_path=GRAPHQL_DATA_PATH / "enums.graphql", + output_path=output_file, + input_file_type="graphql", + assert_func=assert_file_content, + expected_file="enums_ignore_enum_constraints.py", + extra_args=["--ignore-enum-constraints"], + ) + + @pytest.mark.skipif( black.__version__.split(".")[0] == "22", reason="Installed black doesn't support the old style", From 201ef9daab225afceb004d78202889f8f9ba0b25 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 19 Dec 2025 08:48:34 +0000 Subject: [PATCH 4/5] docs: update CLI reference documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated by GitHub Actions --- docs/cli-reference/index.md | 3 +- docs/cli-reference/quick-reference.md | 2 + docs/cli-reference/typing-customization.md | 128 +++++++++++++++++++++ 3 files changed, 132 insertions(+), 1 deletion(-) diff --git a/docs/cli-reference/index.md b/docs/cli-reference/index.md index 1014d131b..cfa85043f 100644 --- a/docs/cli-reference/index.md +++ b/docs/cli-reference/index.md @@ -9,7 +9,7 @@ This documentation is auto-generated from test cases. | Category | Options | Description | |----------|---------|-------------| | 📁 [Base Options](base-options.md) | 5 | Input/output configuration | -| 🔧 [Typing Customization](typing-customization.md) | 16 | Type annotation and import behavior | +| 🔧 [Typing Customization](typing-customization.md) | 17 | Type annotation and import behavior | | 🏷️ [Field Customization](field-customization.md) | 20 | Field naming and docstring behavior | | 🏗️ [Model Customization](model-customization.md) | 26 | Model generation behavior | | 🎨 [Template Customization](template-customization.md) | 16 | Output formatting and custom rendering | @@ -92,6 +92,7 @@ This documentation is auto-generated from test cases. ### I {#i} +- [`--ignore-enum-constraints`](typing-customization.md#ignore-enum-constraints) - [`--ignore-pyproject`](general-options.md#ignore-pyproject) - [`--include-path-parameters`](openapi-only-options.md#include-path-parameters) - [`--input`](base-options.md#input) diff --git a/docs/cli-reference/quick-reference.md b/docs/cli-reference/quick-reference.md index b5e10beac..2aca54ea0 100644 --- a/docs/cli-reference/quick-reference.md +++ b/docs/cli-reference/quick-reference.md @@ -29,6 +29,7 @@ datamodel-codegen [OPTIONS] | [`--allof-merge-mode`](typing-customization.md#allof-merge-mode) | Merge constraints from root model references in allOf schemas. | | [`--disable-future-imports`](typing-customization.md#disable-future-imports) | Prevent automatic addition of __future__ imports in generated code. | | [`--enum-field-as-literal`](typing-customization.md#enum-field-as-literal) | Convert all enum fields to Literal types instead of Enum classes. | +| [`--ignore-enum-constraints`](typing-customization.md#ignore-enum-constraints) | Ignore enum constraints and use base string type instead of Enum classes. | | [`--no-use-specialized-enum`](typing-customization.md#no-use-specialized-enum) | Disable specialized Enum classes for Python 3.11+ code generation. | | [`--output-datetime-class`](typing-customization.md#output-datetime-class) | Specify datetime class type for date-time schema fields. | | [`--strict-types`](typing-customization.md#strict-types) | Enable strict type validation for specified Python types. | @@ -210,6 +211,7 @@ All options sorted alphabetically: - [`--http-headers`](general-options.md#http-headers) - Fetch schema from URL with custom HTTP headers. - [`--http-ignore-tls`](general-options.md#http-ignore-tls) - Disable TLS certificate verification for HTTPS requests. - [`--http-query-parameters`](general-options.md#http-query-parameters) - Add query parameters to HTTP requests for remote schemas. +- [`--ignore-enum-constraints`](typing-customization.md#ignore-enum-constraints) - Ignore enum constraints and use base string type instead of ... - [`--ignore-pyproject`](general-options.md#ignore-pyproject) - Ignore pyproject.toml configuration file. - [`--include-path-parameters`](openapi-only-options.md#include-path-parameters) - Include OpenAPI path parameters in generated parameter model... - [`--input`](base-options.md#input) - Specify the input schema file path. diff --git a/docs/cli-reference/typing-customization.md b/docs/cli-reference/typing-customization.md index 2d0053355..2b6013289 100644 --- a/docs/cli-reference/typing-customization.md +++ b/docs/cli-reference/typing-customization.md @@ -7,6 +7,7 @@ | [`--allof-merge-mode`](#allof-merge-mode) | Merge constraints from root model references in allOf schema... | | [`--disable-future-imports`](#disable-future-imports) | Prevent automatic addition of __future__ imports in generate... | | [`--enum-field-as-literal`](#enum-field-as-literal) | Convert all enum fields to Literal types instead of Enum cla... | +| [`--ignore-enum-constraints`](#ignore-enum-constraints) | Ignore enum constraints and use base string type instead of ... | | [`--no-use-specialized-enum`](#no-use-specialized-enum) | Disable specialized Enum classes for Python 3.11+ code gener... | | [`--output-datetime-class`](#output-datetime-class) | Specify datetime class type for date-time schema fields. | | [`--strict-types`](#strict-types) | Enable strict type validation for specified Python types. | @@ -791,6 +792,133 @@ of Enum classes for all enumerations. --- +## `--ignore-enum-constraints` {#ignore-enum-constraints} + +Ignore enum constraints and use base string type instead of Enum classes. + +The `--ignore-enum-constraints` flag ignores enum constraints and uses +the base type (str) instead of generating Enum classes. This is useful +when you need flexibility in the values a field can accept beyond the +defined enum members. + +!!! tip "Usage" + + ```bash + datamodel-codegen --input schema.json --ignore-enum-constraints # (1)! + ``` + + 1. :material-arrow-left: `--ignore-enum-constraints` - the option documented here + +??? example "Input Schema" + + ```graphql + "Employee shift status" + enum EmployeeShiftStatus { + "not on shift" + NOT_ON_SHIFT + "on shift" + ON_SHIFT + } + + enum Color { + RED + GREEN + BLUE + } + + enum EnumWithOneField { + FIELD + } + ``` + +??? example "Output" + + === "With Option" + + ```python + # generated by datamodel-codegen: + # filename: enums.graphql + # timestamp: 2019-07-26T00:00:00+00:00 + + from __future__ import annotations + + from pydantic import BaseModel + from typing_extensions import TypeAlias + + Boolean: TypeAlias = bool + """ + The `Boolean` scalar type represents `true` or `false`. + """ + + + String: TypeAlias = str + """ + The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. + """ + + + class Color(BaseModel): + __root__: str + + + class EmployeeShiftStatus(BaseModel): + """ + Employee shift status + """ + + __root__: str + + + class EnumWithOneField(BaseModel): + __root__: str + ``` + + === "Without Option" + + ```python + # generated by datamodel-codegen: + # filename: enums.graphql + # timestamp: 2019-07-26T00:00:00+00:00 + + from __future__ import annotations + + from enum import Enum + + from typing_extensions import TypeAlias + + Boolean: TypeAlias = bool + """ + The `Boolean` scalar type represents `true` or `false`. + """ + + + String: TypeAlias = str + """ + The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. + """ + + + class Color(Enum): + BLUE = 'BLUE' + GREEN = 'GREEN' + RED = 'RED' + + + class EmployeeShiftStatus(Enum): + """ + Employee shift status + """ + + NOT_ON_SHIFT = 'NOT_ON_SHIFT' + ON_SHIFT = 'ON_SHIFT' + + + class EnumWithOneField(Enum): + FIELD = 'FIELD' + ``` + +--- + ## `--no-use-specialized-enum` {#no-use-specialized-enum} Disable specialized Enum classes for Python 3.11+ code generation. From fb4e19561d8f6a1641ded105868660c9c8f11097 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 19 Dec 2025 09:45:23 +0000 Subject: [PATCH 5/5] docs: update CLI reference documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated by GitHub Actions --- docs/cli-reference/typing-customization.md | 341 ++++++++------------- 1 file changed, 129 insertions(+), 212 deletions(-) diff --git a/docs/cli-reference/typing-customization.md b/docs/cli-reference/typing-customization.md index 889a62529..315e74e5b 100644 --- a/docs/cli-reference/typing-customization.md +++ b/docs/cli-reference/typing-customization.md @@ -1192,6 +1192,135 @@ of Enum classes for all enumerations. --- +## `--ignore-enum-constraints` {#ignore-enum-constraints} + +Ignore enum constraints and use base string type instead of Enum classes. + +The `--ignore-enum-constraints` flag ignores enum constraints and uses +the base type (str) instead of generating Enum classes. This is useful +when you need flexibility in the values a field can accept beyond the +defined enum members. + +!!! tip "Usage" + + ```bash + datamodel-codegen --input schema.json --ignore-enum-constraints # (1)! + ``` + + 1. :material-arrow-left: `--ignore-enum-constraints` - the option documented here + +??? example "Examples" + + **Input Schema:** + + ```graphql + "Employee shift status" + enum EmployeeShiftStatus { + "not on shift" + NOT_ON_SHIFT + "on shift" + ON_SHIFT + } + + enum Color { + RED + GREEN + BLUE + } + + enum EnumWithOneField { + FIELD + } + ``` + + **Output:** + + === "With Option" + + ```python + # generated by datamodel-codegen: + # filename: enums.graphql + # timestamp: 2019-07-26T00:00:00+00:00 + + from __future__ import annotations + + from pydantic import BaseModel + from typing_extensions import TypeAlias + + Boolean: TypeAlias = bool + """ + The `Boolean` scalar type represents `true` or `false`. + """ + + + String: TypeAlias = str + """ + The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. + """ + + + class Color(BaseModel): + __root__: str + + + class EmployeeShiftStatus(BaseModel): + """ + Employee shift status + """ + + __root__: str + + + class EnumWithOneField(BaseModel): + __root__: str + ``` + + === "Without Option" + + ```python + # generated by datamodel-codegen: + # filename: enums.graphql + # timestamp: 2019-07-26T00:00:00+00:00 + + from __future__ import annotations + + from enum import Enum + + from typing_extensions import TypeAlias + + Boolean: TypeAlias = bool + """ + The `Boolean` scalar type represents `true` or `false`. + """ + + + String: TypeAlias = str + """ + The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. + """ + + + class Color(Enum): + BLUE = 'BLUE' + GREEN = 'GREEN' + RED = 'RED' + + + class EmployeeShiftStatus(Enum): + """ + Employee shift status + """ + + NOT_ON_SHIFT = 'NOT_ON_SHIFT' + ON_SHIFT = 'ON_SHIFT' + + + class EnumWithOneField(Enum): + FIELD = 'FIELD' + ``` + +--- + ## `--no-use-specialized-enum` {#no-use-specialized-enum} Disable specialized Enum classes for Python 3.11+ code generation. @@ -1468,218 +1597,6 @@ Python 3.11+, falling back to standard Enum classes instead. --- -## `--ignore-enum-constraints` {#ignore-enum-constraints} - -Ignore enum constraints and use base string type instead of Enum classes. - -The `--ignore-enum-constraints` flag ignores enum constraints and uses -the base type (str) instead of generating Enum classes. This is useful -when you need flexibility in the values a field can accept beyond the -defined enum members. - -!!! tip "Usage" - - ```bash - datamodel-codegen --input schema.json --ignore-enum-constraints # (1)! - ``` - - 1. :material-arrow-left: `--ignore-enum-constraints` - the option documented here - -??? example "Input Schema" - - ```graphql - "Employee shift status" - enum EmployeeShiftStatus { - "not on shift" - NOT_ON_SHIFT - "on shift" - ON_SHIFT - } - - enum Color { - RED - GREEN - BLUE - } - - enum EnumWithOneField { - FIELD - } - ``` - -??? example "Output" - - === "With Option" - - ```python - # generated by datamodel-codegen: - # filename: enums.graphql - # timestamp: 2019-07-26T00:00:00+00:00 - - from __future__ import annotations - - from pydantic import BaseModel - from typing_extensions import TypeAlias - - Boolean: TypeAlias = bool - """ - The `Boolean` scalar type represents `true` or `false`. - """ - - - String: TypeAlias = str - """ - The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. - """ - - - class Color(BaseModel): - __root__: str - - - class EmployeeShiftStatus(BaseModel): - """ - Employee shift status - """ - - __root__: str - - - class EnumWithOneField(BaseModel): - __root__: str - ``` - - === "Without Option" - - ```python - # generated by datamodel-codegen: - # filename: enums.graphql - # timestamp: 2019-07-26T00:00:00+00:00 - - from __future__ import annotations - - from enum import Enum - - from typing_extensions import TypeAlias - - Boolean: TypeAlias = bool - """ - The `Boolean` scalar type represents `true` or `false`. - """ - - - String: TypeAlias = str - """ - The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. - """ - - - class Color(Enum): - BLUE = 'BLUE' - GREEN = 'GREEN' - RED = 'RED' - - - class EmployeeShiftStatus(Enum): - """ - Employee shift status - """ - - NOT_ON_SHIFT = 'NOT_ON_SHIFT' - ON_SHIFT = 'ON_SHIFT' - - - class EnumWithOneField(Enum): - FIELD = 'FIELD' - ``` - ---- - -## `--no-use-specialized-enum` {#no-use-specialized-enum} - -Disable specialized Enum classes for Python 3.11+ code generation. - -The `--no-use-specialized-enum` flag prevents the generator from using -specialized Enum classes (StrEnum, IntEnum) when generating code for -Python 3.11+, falling back to standard Enum classes instead. - -**Related:** [`--no-use-specialized-enum`](typing-customization.md#no-use-specialized-enum), [`--target-python-version`](model-customization.md#target-python-version) - -!!! tip "Usage" - - ```bash - datamodel-codegen --input schema.json --target-python-version 3.11 --no-use-specialized-enum # (1)! - ``` - - 1. :material-arrow-left: `--no-use-specialized-enum` - the option documented here - -??? example "Input Schema" - - ```graphql - "Employee shift status" - enum EmployeeShiftStatus { - "not on shift" - NOT_ON_SHIFT - "on shift" - ON_SHIFT - } - - enum Color { - RED - GREEN - BLUE - } - - enum EnumWithOneField { - FIELD - } - ``` - -??? example "Output" - - ```python - # generated by datamodel-codegen: - # filename: enums.graphql - # timestamp: 2019-07-26T00:00:00+00:00 - - from __future__ import annotations - - from enum import Enum - from typing import TypeAlias - - Boolean: TypeAlias = bool - """ - The `Boolean` scalar type represents `true` or `false`. - """ - - - String: TypeAlias = str - """ - The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. - """ - - - class Color(Enum): - BLUE = 'BLUE' - GREEN = 'GREEN' - RED = 'RED' - - - class EmployeeShiftStatus(Enum): - """ - Employee shift status - """ - - NOT_ON_SHIFT = 'NOT_ON_SHIFT' - ON_SHIFT = 'ON_SHIFT' - - - class EnumWithOneField(Enum): - FIELD = 'FIELD' - ``` - ---- - ## `--output-datetime-class` {#output-datetime-class} Specify datetime class type for date-time schema fields.