NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #972 most downloaded on PyPI
Datamodel Code Generator
Latest stable
0.92.0
Last release 10 days ago
10 Nov 2026
Ships fairly regularly
a new release about every 2 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
1 version withdrawn
withdrawn after publishing
7 years old
296 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
Preserved additionalProperties value constraints change generated output - JSON Schema additionalProperties (and propertyNames/mapping) value schemas
additionalProperties (and propertyNames/mapping) value schemas that carry constraints (e.g. minimum/maximum, minLength/maxLength/pattern, array item constraints, allOf-merged primitives) now retain those constraints in the generated model instead of dropping them. This produces new TypeAlias/RootModel/TypeAliasType definitions and changes dict value type hints, so output differs for existing schemas. For example, a mapping value that previously generated dict[str, Literal['fixed']] now generates a dedicated alias preserving the constraints (#3616):# Before
class DictModel(RootModel[dict[str, Literal['fixed']]]):
root: dict[str, Literal['fixed']]
# After
DictModelAdditionalProperty = TypeAliasType(
"DictModelAdditionalProperty",
Annotated[Literal['fixed'], Field(max_length=100, min_length=1)],
)
class DictModel(RootModel[dict[str, DictModelAdditionalProperty]]):
root: dict[str, DictModelAdditionalProperty]
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.69.0...0.70.0
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Discriminated unions with duplicate or unresolvable discriminator values now fall back to a plain union - When a discriminated union contains variants
RootModel/type-alias wrappers, None/str members, or otherwise lack a resolvable discriminator literal, the generator no longer emits Field(..., discriminator='...') and instead produces a regular union. Previously such schemas emitted a discriminator= argument. Users regenerating models from these schemas will see the discriminator keyword removed from the affected fields (#3603)# Before (invalid duplicate-value discriminator was emitted):
class GroupedItem(RootModel[Item | ItemReference]):
root: Item | ItemReference = Field(..., discriminator='type')
# After (falls back to a plain union when variants are not valid discriminated members):
class MixedItem(RootModel[str | ItemReference | None]):
root: str | ItemReference | None
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.68.1...0.69.0
Skip docs preview deploy for dependabot PRs by @gaborbernat in https://github.com/koxudaxi/datamodel-code-generator/pull/3576
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.68.0...0.68.1
Ruff formatting failures now raise instead of being ignored - Ruff subprocess calls previously ran with check=False and used their stdout regardless o
check=False and used their stdout regardless of exit code, so a failed ruff run silently produced (possibly empty or partial) output. _run_ruff_command now raises RuntimeError when ruff exits non-zero (except the allowed check-with-remaining-diagnostics case), and _find_ruff_path raises a RuntimeError with an install hint when ruff is missing instead of falling back to "ruff". Workflows that relied on generation silently succeeding despite a ruff error will now fail with an exception. (#3561)--enable-command-header now redacts sensitive HTTP options - When --enable-command-header is combined with --http-headers or --http-query-parameters, the reproducibility command line embedded in generated files now writes <redacted> in place of those values instead of the literal arguments. Generated file headers change for these flag combinations, so committed output or snapshot tests will differ. (#3561)RootModel now synchronizes and renders model_config derived from config objects (e.g. regex_engine, frozen) that were previously dropped, and non-dict config objects are now applied in the base model. Generated output for affected pydantic v2 root models may now include a model_config = ConfigDict(...) that was not emitted before. (#3561)generate() keeps str inputs as inline source text. Pass a Path to input_ for local file input; if a failed string input resolves to an existing path, generate() warns and recommends using Path. (#3573)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.67.0...0.68.0
Auto input-type CSV fallback is now conditional - When --input-file-type auto is used, infer_input_type() previously treated any YAML parse failure as
--input-file-type auto is used, infer_input_type() previously treated any YAML parse failure as CSV data. It now falls back to CSV only when the text looks like CSV (non-empty lines with consistent, non-zero comma counts). Inputs that were previously inferred as csv — including malformed JSON/YAML and ragged CSV with inconsistent column counts (e.g. id,name,tel\n1,taro\n) — will no longer be inferred as CSV. (#3536)extra-args no longer undergoes shell expansion - The Action previously appended extra-args directly into the shell command (datamodel-codegen "${ARGS[@]}" ${{ inputs.extra-args }}), so the value was subject to word-splitting, glob expansion, variable expansion, and command substitution. It is now tokenized with Python's shlex.split. Workflows that relied on shell features inside extra-args (globs like *.json, variables like $HOME, or command substitution $(...)) will no longer have them expanded and must pass literal, individually-quoted arguments instead. (#3542)extras input is now validated against a whitelist - Previously any value passed to the extras input was accepted and injected into the pip install spec. It is now validated against the fixed set graphql, http, validation, ruff, all; any other value now fails the install step with ::error::Unsupported extras value: <value> instead of being passed through. Workflows passing extras values outside this set will now error. (#3542)auto inference, input that fails YAML parsing and does not look like CSV now raises Error rather than falling back to CSV and attempting generation. The error message was also expanded to include the underlying YAML parser error, e.g. Can't infer input file type from the input data. YAML parser error: <Type>: <detail>. Please specify the input file type explicitly with --input-file-type option. Workflows depending on the old blanket-CSV fallback must now pass --input-file-type csv explicitly. (#3536)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.66.3...0.67.0
Update CHANGELOG for 0.66.2 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3511
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.66.2...0.66.3
Update CHANGELOG for 0.66.1 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3507
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.66.1...0.66.2
Add schema validators by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3228
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.66.0...0.66.1
msgspec nullable annotated fields now place None outside Annotated - For msgspec.Struct models, nullable fields that carry Meta/Annotated constraints
None outside Annotated - For msgspec.Struct models, nullable fields that carry Meta/Annotated constraints no longer wrap the type in Optional inside the Annotated[...]. The None member is now emitted as a separate union arm outside the Annotated wrapper, which changes the generated type hints and the resulting imports (Optional is dropped when no longer needed). This is required for the generated models to validate correctly at runtime under msgspec, but it changes output for existing users. (#3495)# Before
from typing import Annotated, Optional, Union
name: Union[Annotated[Optional[str], Meta(max_length=5)], UnsetType] = UNSET
# After
from typing import Annotated, Union
name: Union[Annotated[str, Meta(max_length=5)], None, UnsetType] = UNSET
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.65.1...0.66.0
Update CHANGELOG for 0.65.0 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3470
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.65.0...0.65.1
Fix release draft breaking change notes by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3440
!!set tags now rejected - load_yaml now validates all YAML input and raises a yaml.YAMLError when it encounters the unsupported tag:yaml.org,2002:set (!!set) tag. Previously such input was loaded silently (constructed as a Python set). YAML schemas or sample data that relied on !!set tags will now fail to load with an "Unsupported YAML tag" error. This validation runs unconditionally on every YAML load and is not gated behind any opt-in flag (#3447)bool instead of Literal[True]/Literal[False] - When generating msgspec.Struct models (--output-model-type msgspec.Struct), a JSON Schema const with a boolean value now produces a plain bool type instead of a boolean Literal, because msgspec does not support boolean Literal tag values at runtime. Output for other model types (e.g. Pydantic) is unchanged. Existing msgspec users with boolean-const fields will see different generated output. (#3462)msgspec.Struct output, combined (oneOf/anyOf) object schemas that share a required literal discriminator field with int/str values now have a discriminator inferred and are emitted as tagged Struct unions (tag_field=..., tag=...). This changes the generated class definitions for existing msgspec users whose schemas match this shape. (#3462)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.64.1...0.65.0
Optional primitive const fields no longer emit the const value as an injected default - Optional primitive const properties without a schema default n
const fields no longer emit the const value as an injected default - Optional primitive const properties without a schema default now render as nullable/omittable (Literal[...] | None = None) instead of being populated with the const value when the input key is omitted. Regenerated code and snapshot tests may change. (#3434)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.64.0...0.64.1
Pin deprecation warning stacklevel by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3363
--disable-future-imports - When --disable-future-imports is set (no from __future__ import annotations and no native PEP 649 deferred evaluation on Python < 3.14), self-referencing and forward-referencing field annotations in regular BaseModel classes are now emitted as quoted forward references instead of bare names. Previously such annotations were left unquoted, producing invalid code that raised NameError (Ruff F821) at class-evaluation time. Output for the common case (with from __future__ import annotations or Python 3.14 native deferred annotations) is unchanged. Users who snapshot/golden-file generated output for the --disable-future-imports configuration with self-referencing models will see the annotation change from unquoted to quoted, e.g. children: Optional[List[Node]] → children: Optional[List["Node"]]. (#3387)constr() for string fields carrying minItems/maxItems by @DarkaMaul in https://github.com/koxudaxi/datamodel-code-generator/pull/3353Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.63.0...0.64.0
--check output now uses POSIX-style paths - File paths in --check diagnostic output are now normalized with Path.as_posix() instead of str(path). On P
--check output now uses POSIX-style paths - File paths in --check diagnostic output are now normalized with Path.as_posix() instead of str(path). On POSIX systems the output is unchanged, but on Windows the diff headers and MISSING:/EXTRA: lines now use forward slashes (models/foo.py) instead of backslashes (models\foo.py). Tooling or snapshot tests that parse --check output on Windows may need updating. (#3287)Authorization, Cookie, and Proxy-Authorization when a remote schema fetch follows a cross-origin redirect. (GHSA-r5vv-ff45-prp2)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.62.0...0.63.0
Local JSON Schema $ref references outside the input base path now emit deprecation warnings - Relative path refs (e.g., $ref: "../other/schema.json")…
str | None) in msgspec Structs were incorrectly rendered with = None. They are now correctly rendered without a default assignment (e.g., label: str | None instead of label: str | None = None), which means callers must provide the value explicitly (#3292)minItems/maxItems schema constraints on array fields were previously silently ignored for msgspec output. They now render as Annotated[list[T], Meta(min_length=..., max_length=...)] when --use-annotated is enabled (e.g., list[Pet] becomes Annotated[list[Pet], Meta(max_length=10, min_length=1)]) (#3292)kw_only=True - When a child Struct inherits optional fields from a parent and adds required fields, the child now renders with kw_only=True as a base class kwarg (e.g., class Child(Base, kw_only=True):), changing the calling convention to keyword-only arguments (#3292)float() calls instead of math imports - Generated code previously rendered inf, -inf, and nan (with from math import inf, nan). Now renders float('inf'), float('-inf'), and float('nan') without the math import. Semantically equivalent but changes generated output. (#3289)Decimal() objects - condecimal() constraints previously used bare int/float values (e.g., condecimal(ge=0, le=1000)). Now uses Decimal objects (e.g., condecimal(ge=Decimal('0'), le=Decimal('1000'))) with an added from decimal import Decimal import in generated code. (#3289)gt: 0.5 becomes ge: 1, lt: 2.5 becomes le: 2, and multiple_of: 1 is dropped entirely. Previously these fractional values were passed through as-is to conint() or Field(). (#3289)min_items and max_items schema constraints on array fields are now emitted as Meta(min_length=..., max_length=...) annotations in msgspec output. Previously these constraints were silently ignored. (#3289)= None - Required nullable fields in msgspec Structs previously received a = None default assignment. Now they are rendered without a default, requiring callers to provide the value explicitly. (#3289)extra_items now uses direct identifiers instead of string forward references - When additionalProperties references another type, the generated extra_items= keyword argument changed from a quoted string to a bare identifier (e.g., extra_items='BaseExtra' → extra_items=BaseExtra). The generated code remains valid because files include from __future__ import annotations, but the textual output differs (#3301)TypedDict('Name', {...})) are now rendered before the definition instead of after it. Previously the docstring appeared as a string literal following the assignment; it now appears as a comment block preceding it (#3301)uuid.UUID instead of pydantic.UUID2 - Schemas using "format": "uuid2" now generate UUID imported from the uuid standard library instead of the non-existent UUID2 from pydantic. This is a bug fix since pydantic.UUID2 was never a valid Pydantic v2 type (the old generated code would raise ImportError), but the generated import and type annotation will differ for any schema using this format (#3297)not field.field and (not field.required or field.use_default_with_required or field.data_type.is_optional or field.nullable) to not field.field and (not field.required or field.use_default_with_required). Users with custom msgspec templates that replicate the old logic should update accordingly (#3292)not field.required or field.use_default_with_required or field.data_type.is_optional or field.nullable to not field.required or field.use_default_with_required. Custom templates derived from the built-in msgspec template may need to be updated. (#3289)TypedDictFunction.jinja2 template restructured - The built-in functional TypedDict template moved the description block from after the class definition to before it and added support for field-level docstrings. Users with custom templates that were based on or extend this template may need to update accordingly (#3301)xs:include, xs:import, xs:redefine, or xs:override with a schemaLocation that resolves outside the input base directory now raises an unconditional error. Previously, these references were silently resolved regardless of location. Users with XML schemas that include files from parent or sibling directories must move the included schemas under the input directory before generating models. (#3308)$ref references outside the input base path now emit deprecation warnings - Relative path refs (e.g., $ref: "../other/schema.json") and file:// URL refs that resolve outside the input base directory now emit a FutureWarning under the default behavior (no --allow-remote-refs flag). Previously these were silently resolved. Pass --allow-remote-refs to suppress the warning, or move referenced schemas under the input directory. (#3308)--no-allow-remote-refs now blocks file:// URLs and local refs outside the base path - Previously --no-allow-remote-refs only blocked HTTP(S) $ref fetching. It now also blocks file:// URL references and relative local $ref references that resolve outside the input base path. Users who rely on file:// refs or out-of-tree local refs with --no-allow-remote-refs must switch to --allow-remote-refs or restructure their schemas. (#3308)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.61.0...0.62.0
HTTP(S) schema fetching now blocks localhost, loopback, private, link-local, reserved, and other non-public network targets by default. Users who inte
--allow-private-network or set allow_private_network=True.--url and remote JSON Schema/OpenAPI $ref URLs. (GHSA-rfr2-mq9m-x2qx, GHSA-954p-556p-r752)$ref fetching remains controlled by --allow-remote-refs; non-public remote references additionally require --allow-private-network.Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.60.2...0.61.0
Fixed code injection from schema-provided default_factory values. (GHSA-386q-5hp3-95m9)
default_factory values. (GHSA-386q-5hp3-95m9)x-python-type extension values. (GHSA-m34r-v34r-rf9q)comment entries supplied through --extra-template-data. (GHSA-wjv6-jcfj-mf9r)--validators or --extra-template-data. (GHSA-8m8r-38jm-f355)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.60.1...0.60.2
Fixed code injection from GraphQL union descriptions containing carriage returns. (GHSA-j884-q54q-mmx3)
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.60.0...0.60.1
Avro record field defaults are no longer emitted as generated Python defaults. Avro defaults describe reader behavior, not Python model construction d
default. This also applies to Avro schemas embedded in AsyncAPI multi-format schemas. (#3256)xs:decimal now generates Decimal instead of float; xs:dateTime defaults to standard-library datetime because XML Schema allows values without a timezone; xs:dateTimeStamp remains AwareDatetime; xs:duration and xs:yearMonthDuration now generate str, while xs:dayTimeDuration still generates timedelta. (#3248)= [] can now be omitted when constructing the generated model. (#3255)bytes defaults are now generated as bytes literals instead of strings, including escaped byte sequences. (#3252)--output-datetime-class is respected for XML Schema xs:dateTime and xs:dateTimeStamp when explicitly provided. Without the option, the XML Schema defaults above are used. (#3266)--set-default-enum-member. The default behavior is not changed to force enum member references. (#3264)const values are not treated as generated Python defaults unless the schema also defines a default. XML Schema fixed keeps its XSD value-constraint behavior. (#3268)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.59.1...0.60.0
Update CHANGELOG for 0.59.0 by @dcg-generated-docs[bot] in https://github.com/koxudaxi/datamodel-code-generator/pull/3216
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.59.0...0.59.1
Add deprecation registry and docs by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3188
propertyNames constraints - When a JSON Schema uses both patternProperties and propertyNames, the generated dict key type now merges constraints from both. Previously, propertyNames constraints such as minLength, maxLength, and $ref could be ignored when patternProperties was present. Regenerated code may produce stricter key types and reject data that was previously accepted by less-strict generated models. (#3192)additionalProperties now generates a typed __pydantic_extra__ field for Pydantic v2 models - When a JSON Schema defines schema-valued additionalProperties, generated Pydantic v2 models now include __pydantic_extra__: dict[str, <type>]. Previously, these models only allowed extra fields without typing their values. This changes generated output and makes Pydantic validate extra field values at runtime. (#3205)--use-annotated may change - Dataclass field assignment detection now accounts for constraints moved into Annotated[...]. Generated dataclass fields may be reordered so fields without defaults come before fields with defaults. (#3203)--input-file-type auto) now recognizes AsyncAPI, Avro, and Protocol Buffers inputs - Inputs that previously fell back to JSON/YAML handling or failed detection may now be detected as one of these formats. (#3194, #3195, #3198)pydantic>=2,<3 to pydantic>=2.6,<3 was reverted before this release. The final dependency range for Python < 3.14 remains pydantic>=2,<3. (#3210, #3215)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.58.0...0.59.0
Added --serialization-aliases for Pydantic v2 serialization alias mapping.
--serialization-aliases for Pydantic v2 serialization alias mapping. (#3146)--openapi-include-info-version to emit OPENAPI_INFO_VERSION from OpenAPI info.version. (#3176)--use-object-type to generate object instead of Any for unspecified JSON Schema object and array values. (#3177)AliasChoices - Fields that previously generated duplicate entries such as AliasChoices('endDate', 'end_date', 'endDate') now generate each alias once. Runtime behavior is equivalent, but exact generated output changes. (#3146)additionalProperties/unevaluatedProperties, const: null, complex enum values, all-false patternProperties, non-string propertyNames, boolean array item schemas, contains, minProperties/maxProperties, and enum references through allOf now generate more accurate annotations or constraints. Users with snapshots or exact-output checks may see diffs. (#3167)TypedDict from both typing and typing_extensions; TypedDict is kept only where required. (#3155)$ref types in allOf, additionalProperties with $ref, heterogeneous root constraints, and unresolved discriminator fields now generate more valid types/fields. (#3168)allOf schemas now generate root-style payload types - Primitive-only allOf and top-level allOf combined with oneOf/anyOf now generate RootModel/root payload types instead of empty or object-like models. Code instantiating the previous generated classes may need updates. (#3169, #3171)multipleOf intersections in allOf now use the least common multiple - For example, multipleOf: 5 combined with multipleOf: 10 now generates multiple_of=10 instead of incorrectly keeping the first value. Decimal multiples are handled similarly. (#3172)contentEncoding, contentMediaType, contentSchema, externalDocs, and xml are included in generated json_schema_extra when present in the input schema, even without --model-extra-keys. (#3175)--output-datetime-class now rejects incompatible TypedDict and Dataclass output combinations - Pydantic-specific datetime classes with typing.TypedDict, and incompatible dataclass API usage, now raise errors instead of silently producing fallback output. (#3155, #3169)false inside allOf now raises SchemaParseError - Unsatisfiable allOf branches are reported instead of generating incorrect models. false branches in oneOf/anyOf are filtered where appropriate. (#3168)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.57.0...0.58.0
--use-default no longer makes required fields nullable - Previously, --use-default turned required fields into optional nullable fields (e.g., status:
--use-default no longer makes required fields nullable - Previously, --use-default turned required fields into optional nullable fields (e.g., status: str | None = 'active'). Now required fields keep their original non-nullable type and just get the default value rendered (e.g., status: str = 'active'). Users whose downstream code depends on these fields being Optional/nullable will need to update. (#3054)--use-default - Previously, required fields referencing models (e.g., shipping_address: Address) inconsistently rendered defaults with validate_default=True while scalar required fields did not. Now all required fields consistently omit defaults unless --use-default is passed. Users who relied on the previous behavior where model-ref required fields had defaults rendered will see those defaults removed. (#3054)field.use_default_with_required - The built-in templates for BaseModel, dataclass, pydantic_v2/dataclass, and msgspec were updated to check field.use_default_with_required alongside field.required when deciding whether to render defaults. Custom templates that replicate the old default-rendering logic (e.g., {%- if not field.required %}) will still work but won't support the new --use-default behavior for required fields. To get the updated behavior, custom templates should change conditions like not field.required to (not field.required or field.use_default_with_required). (#3054)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.56.1...0.57.0
Fix --base-class-map and --enum-field-as-literal-map long inline json support by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/p
--base-class-map and --enum-field-as-literal-map long inline json support by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/3075Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.56.0...0.56.1
Update release draft model and preserve breaking changes by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3057
Field(default_value, validate_default=True) instead of default_factory=lambda: TypeAdapter(...).validate_python(...) or default_factory=lambda: Model.model_validate(...). This produces simpler, more readable code but changes the generated output format. (#3050)TypeAdapter from pydantic since validate_default=True handles validation natively. (#3050)Field(<raw_value>, validate_default=True) instead of default_factory=lambda: Model.model_validate(...), default_factory=lambda: TypeAdapter(...).validate_python(...), or default_factory=lambda: Model(...). Empty collection defaults changed from default_factory=list/default_factory=dict to Field([], validate_default=True)/Field({}, validate_default=True). The generated code is semantically equivalent under Pydantic v2 but textually different, which will break snapshot tests or tooling that matches exact output. pydantic.TypeAdapter is no longer imported in generated code. (#3070)validate_default=True instead of default_factory lambdas - Fields with structured defaults (dicts, lists, or scalars referencing Pydantic models/RootModels) previously generated default_factory=lambda: ModelName.model_validate(value) or default_factory=lambda: ModelName(value). They now generate Field(value, validate_default=True), producing simpler but different output. Empty collection defaults changed from default_factory=list/default_factory=dict to Field([], validate_default=True)/Field({}, validate_default=True). Users who regenerate code will see different output. (#3071)
Before:count: CountType | None = Field(default_factory=lambda: CountType(10))
items: dict[str, Item] | None = Field(default_factory=dict, title='Items')
After:count: CountType | None = Field(10, validate_default=True)
items: dict[str, Item] | None = Field({}, title='Items', validate_default=True)
validate_default=True instead of default_factory=lambda: - Fields with structured defaults (dicts/lists) that reference Pydantic models previously generated default_factory=lambda: Model.model_validate(...) or default_factory=lambda: TypeAdapter(Type).validate_python(...) patterns. They now generate the raw default value directly with validate_default=True (e.g., Field({'key': 'val'}, validate_default=True) instead of Field(default_factory=lambda: Model.model_validate({'key': 'val'}))). This changes the generated code output and may affect users who depend on the exact generated code structure, pin generated output in tests, or use custom post-processing. The runtime behavior should be equivalent for Pydantic v2 users. (#3072)TypeAdapter import removed from generated code - Generated code no longer imports pydantic.TypeAdapter for default value handling. Code that previously used TypeAdapter(...).validate_python(...) in default factories now uses inline defaults with validate_default=True. (#3072)int and bool discriminator values (e.g., Literal[1] instead of Literal['1']), which changes generated code for schemas using integer discriminator mappings. (#3072)ValidatedDefault and WrappedDefault classes removed - These internal classes were exported from datamodel_code_generator.model.base and have been removed. Code importing these types will break:# Before (broken)
from datamodel_code_generator.model.base import ValidatedDefault, WrappedDefault
(#3050)SUPPORTS_WRAPPED_DEFAULT and SUPPORTS_VALIDATED_DEFAULT class variables removed - These flags were removed from the DataModel base class. Custom model classes that override these variables will see attribute errors. (#3050)ValidatedDefault and WrappedDefault removed - The datamodel_code_generator.model._types module was deleted and ValidatedDefault/WrappedDefault are no longer exported from datamodel_code_generator.model.base. Code that imports or subclasses these types will break. The SUPPORTS_WRAPPED_DEFAULT and SUPPORTS_VALIDATED_DEFAULT class variables were removed from DataModel and its subclasses; custom model classes referencing these attributes will need updating. (#3070)WrappedDefault, ValidatedDefault classes and SUPPORTS_WRAPPED_DEFAULT, SUPPORTS_VALIDATED_DEFAULT class variables - The WrappedDefault and ValidatedDefault classes from datamodel_code_generator.model._types (re-exported via datamodel_code_generator.model.base) have been deleted. The DataModel class variables SUPPORTS_WRAPPED_DEFAULT and SUPPORTS_VALIDATED_DEFAULT have also been removed. Code that imports or references these will break. (#3071)--allow-remote-refs / --no-allow-remote-refs CLI option and allow_remote_refs config field - Remote $ref fetching over HTTP/HTTPS now emits a deprecation warning by default. Pass --allow-remote-refs to suppress the warning, or --no-allow-remote-refs to block remote fetching entirely. In a future version, remote fetching will be disabled by default. Users relying on remote $ref resolution should add --allow-remote-refs to their invocations to avoid the deprecation warning and prepare for the future default change. (#3072)SchemaFetchError exception for HTTP fetch failures - Remote schema fetching now raises SchemaFetchError (instead of propagating raw httpx exceptions) on HTTP errors, non-2xx status codes, or unexpected HTML responses. Users catching specific httpx exceptions from remote ref resolution will need to catch SchemaFetchError instead. (#3072)$ref now raises Error instead of FileNotFoundError - Previously, when a $ref pointed to a non-existent local file, a raw FileNotFoundError propagated to callers. Now it raises datamodel_code_generator.Error with the message "$ref file not found: <path>". Programmatic users catching FileNotFoundError specifically will need to catch Error instead (#3051)SchemaFetchError instead of propagating raw exceptions - HTTP errors (4xx/5xx status codes), unexpected HTML responses, and transport errors (DNS, timeout, connection) that previously resulted in downstream YAML/JSON parse errors or raw httpx exceptions now raise SchemaFetchError (a subclass of Error) before parsing is attempted. Users catching specific parse errors or httpx exceptions for these scenarios will need to update their error handling (#3051)SchemaFetchError instead of raw httpx exceptions - The get_body() function in http.py now catches HTTP errors and raises SchemaFetchError (a new Error subclass) for HTTP status >= 400, network failures, and unexpected HTML responses. Code that caught raw httpx exceptions from remote schema fetching will need to catch SchemaFetchError instead. (#3071)$ref fetching now emits FutureWarning without --allow-remote-refs - Fetching remote HTTP/HTTPS $ref references without explicitly passing --allow-remote-refs now emits a FutureWarning deprecation warning. In a future version, remote fetching will be disabled by default. Users relying on implicit remote ref fetching should add --allow-remote-refs to suppress the warning. (#3071)SchemaFetchError with validation of response content type - Previously, fetching a remote $ref that returned an HTML error page would silently pass the HTML through as schema content. Now it raises SchemaFetchError if the response has text/html content type or a 4xx/5xx status code. This may cause previously-silent failures to become loud errors. (#3072)$ref fetching now emits FutureWarning - When a $ref resolves to an HTTP(S) URL and --allow-remote-refs is not explicitly passed, the tool still fetches the remote reference but emits a FutureWarning. This may cause failures in environments running with -W error (warnings as errors) or strict warning filters. Pass --allow-remote-refs explicitly to suppress the warning (#3051)$ref fetching now emits a FutureWarning - When the parser encounters an HTTP/HTTPS $ref without --allow-remote-refs being explicitly set, a FutureWarning is emitted warning that remote fetching will be disabled by default in a future version. Pass --allow-remote-refs to silence the warning, or --no-allow-remote-refs to block remote fetching immediately. (#3070)fields guard - All six type alias templates (TypeAliasAnnotation.jinja2, TypeAliasType.jinja2, TypeStatement.jinja2, UnionTypeAliasAnnotation.jinja2, UnionTypeAliasType.jinja2, UnionTypeStatement.jinja2) now wrap the main body in {% if fields %}...{% else %} blocks that fall back to {{ base_class }} when no fields are present. Users with custom copies of these templates must add the same guard or handle the empty-fields case. (#3070)fields guard and base_class fallback - The built-in templates TypeAliasAnnotation.jinja2, TypeAliasType.jinja2, TypeStatement.jinja2, and their Union variants now wrap field access in {%- if fields %}...{%- else %} blocks with a base_class fallback for empty field lists. Users with custom templates derived from the old versions will need to add similar guards. (#3071)TypeAliasAnnotation.jinja2, TypeAliasType.jinja2, TypeStatement.jinja2, and their Union variants) now handle an empty fields list with a fallback to base_class - If you have custom copies of these templates, they need to be updated to include the new {%- if fields %}...{%- else %}...{%- endif %} branching logic. Without this update, custom templates may error when fields is empty. (#3072)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.55.0...0.56.0
Users running datamodel-code-generator with Pydantic v1 installed must upgrade to Pydantic v2. The previously deprecated v1 compatibility layer has be…
datamodel-codegen without specifying --output-model-type now generates Pydantic v2 models (pydantic_v2.BaseModel) instead of Pydantic v1 models (pydantic.BaseModel). Users who depend on the previous default behavior must now explicitly specify --output-model-type pydantic.BaseModel to continue generating Pydantic v1 compatible code. (#3029)RootModel instead of __root__ fields, native union syntax (str | None) instead of Optional[str], and Pydantic v2 validator/serializer decorators. Existing code that consumes generated models may need updates to work with the new Pydantic v2 output format. (#3029)pydantic.BaseModel output model type has been completely removed. Generated code now only supports Pydantic v2 patterns including RootModel instead of __root__, model_rebuild() instead of update_forward_refs(), and model_config instead of class Config. Users generating Pydantic v1 models must migrate to v2 output. (#3031)pydantic/BaseModel.jinja2 → use pydantic_v2/BaseModel.jinja2pydantic/BaseModel_root.jinja2 → use pydantic_v2/RootModel.jinja2pydantic/Config.jinja2 → removed (v2 uses model_config dict)
(#3031)--output-model-type pydantic.BaseModel removed - The pydantic.BaseModel value for --output-model-type is no longer valid. Use pydantic_v2.BaseModel instead (now the default). (#3031)datamodel_code_generator.util: model_dump(), model_validate(), get_fields_set(), model_copy(). Use Pydantic v2 methods directly (obj.model_dump(), cls.model_validate(), etc.). (#3031)datamodel_code_generator.model.pydantic module removed - The entire Pydantic v1 model module including BaseModel, CustomRootType, DataModelField, DataTypeManager, and dump_resolve_reference_action has been removed. Use datamodel_code_generator.model.pydantic_v2 instead. (#3031)pydantic>=1.5 to pydantic>=2,<3. Users with pydantic v1 installed must upgrade to pydantic v2 before using datamodel-code-generator (#3027)datamodel_code_generator.util: get_pydantic_version(), is_pydantic_v2(), model_validator(), field_validator(), and ConfigDict. Users who imported these internal utilities directly must update their code to use pydantic's native APIs (#3027)datamodel_code_generator.pydantic_patch module - The entire pydantic compatibility patching module was removed. Any code importing from this module will fail (#3027)packaging dependency - The packaging library is no longer a dependency. Code that relied on it being transitively available should add it explicitly (#3027)ValidatedDefault by @keyz in https://github.com/koxudaxi/datamodel-code-generator/pull/3040Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.54.1...0.55.0
Add dismissible announce bar to docs site by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/3004
--use-annotated and --use-non-positive-negative-number-constrained-types by @torarvid in https://github.com/koxudaxi/datamodel-code-generator/pull/3015Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.54.0...0.54.1
Enum member names from oneOf/anyOf const constructs now use title field when provided - Previously, when creating enums from oneOf/anyOf constructs wi
title field when provided - Previously, when creating enums from oneOf/anyOf constructs with const values, the title field was incorrectly ignored and enum member names were generated using the pattern {type}_{value} (e.g., integer_200). Now, when a title is specified, it is correctly used as the enum member name (e.g., OK instead of integer_200). Users who have code depending on the previously generated enum member names will need to update their references. (#2975)
Before:class StatusCode(IntEnum):
integer_200 = 200
integer_404 = 404
integer_500 = 500
After:class StatusCode(IntEnum):
OK = 200
Not_Found = 404
Server_Error = 500
int: int, list: list[str], dict: dict[str, Any]), the field is now renamed with a trailing underscore (e.g., int_) and an alias is added to preserve the original JSON field name. This prevents Python syntax issues and shadowing of builtin types. Previously, such fields were generated as-is (e.g., int: int | None = None), which could cause code that shadows Python builtins. After this change, the same field becomes int_: int | None = Field(None, alias='int'). This affects fields named: int, float, bool, str, bytes, list, dict, set, frozenset, tuple, and other Python builtins when their type annotation uses the matching builtin type. (#2968)$ref was combined with non-standard fields like markdownDescription, if, then, else, or other extras not in the whitelist, the generator would merge schemas and potentially create duplicate models (e.g., UserWithExtra alongside User). Now, only whitelisted schema-affecting extras (currently just const) trigger merging. This means:
properties:
user:
$ref: "#/definitions/User"
nullable: true
markdownDescription: "A user object"
Before: Could generate a merged UserWithMarkdownDescription model
After: Directly uses User | None reference (#2993)--capitalise-enum-members - Previously, enum values like replace, count, index would generate REPLACE_, COUNT_, INDEX_ when using --capitalise-enum-members. Now they correctly generate REPLACE, COUNT, INDEX. The underscore suffix is only added when --use-subclass-enum is also used AND the lowercase name conflicts with builtin type methods. Users relying on the previous naming (e.g., referencing MyEnum.REPLACE_ in code) will need to update to use the new names without trailing underscores. (#2999)$ref with inline keywords now include merged metadata - When a schema property uses $ref alongside additional keywords (e.g., const, enum, readOnly, constraints), the generator now correctly merges metadata (description, title, constraints, defaults, readonly/writeOnly) from the referenced schema into the field definition. Previously, this metadata was lost. For example, a field like type: Type may now become type: Type = Field(..., description='Type of this object.', title='type') when the referenced schema includes those attributes. This also affects additionalProperties and OpenAPI parameter schemas. (#2997)allOf's or anyOf's objects by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2975Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.53.0...0.54.0
Parser subclass signature change - The Parser base class now requires two generic type parameters: Parser[ParserConfigT, SchemaFeaturesT] instead of j
Parser base class now requires two generic type parameters: Parser[ParserConfigT, SchemaFeaturesT] instead of just Parser[ParserConfigT]. Custom parser subclasses must be updated to include the second type parameter. (#2929)# Before
class MyCustomParser(Parser["MyParserConfig"]):
...
# After
class MyCustomParser(Parser["MyParserConfig", "JsonSchemaFeatures"]):
...
schema_features property required - Custom parser subclasses must now implement the schema_features abstract property that returns a JsonSchemaFeatures (or subclass) instance. (#2929)from functools import cached_property
from datamodel_code_generator.parser.schema_version import JsonSchemaFeatures
from datamodel_code_generator.enums import JsonSchemaVersion
class MyCustomParser(Parser["MyParserConfig", "JsonSchemaFeatures"]):
@cached_property
def schema_features(self) -> JsonSchemaFeatures:
return JsonSchemaFeatures.from_version(JsonSchemaVersion.Draft202012)
_create_default_config refactored to use class variable - Subclasses that override _create_default_config should now set the _config_class_name class variable instead. The base implementation uses this variable to dynamically instantiate the correct config class. (#2929)# Before
@classmethod
def _create_default_config(cls, options: MyConfigDict) -> MyParserConfig:
# custom implementation...
# After
_config_class_name: ClassVar[str] = "MyParserConfig"
# No need to override _create_default_config if using standard config creation
BaseModel_root.jinja2 or RootModel.jinja2, the condition for including default values has changed from field.required to (field.required and not field.has_default). Update your custom templates if you override these files. (#2960)default: 1 will generate __root__: int = 1 (Pydantic v1) or root: int = 1 (Pydantic v2) instead of just __root__: int or root: int. This may affect code that relied on the previous behavior where RootModel fields had no default values. (#2960)default_factory - Previously, required fields with list-type defaults (like __root__: list[ID] = ['abc', 'efg']) were generated with direct list assignments. Now they correctly use Field(default_factory=lambda: ...) which follows Python best practices for mutable defaults. This changes the structure of generated code for root models and similar patterns with list defaults. (#2958)
Before:class Family(BaseModel):
__root__: list[ID] = ['abc', 'efg']
After:class Family(BaseModel):
__root__: list[ID] = Field(
default_factory=lambda: [ID.parse_obj(v) for v in ['abc', 'efg']]
)
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.52.2...0.53.0
Add support for multiple base classes in base_class_map and customBasePath by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.52.1...0.52.2
Add deprecation warning for default output-model-type by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2910
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.52.0...0.52.1
Union fields with titles now wrapped in named models when --use-title-as-name is enabled - Previously, union-typed fields with a title were generated
--use-title-as-name is enabled - Previously, union-typed fields with a title were generated as inline union types (e.g., TypeA | TypeB | TypeC | None). Now they generate a separate wrapper model using the title name, and the field references this wrapper type (e.g., ProcessingStatusUnionTitle | None). This affects code that directly accesses union field values, as they now need to access the .root attribute (Pydantic v2) or .__root__ (Pydantic v1) of the wrapper model. (#2889)
Before:class ProcessingTaskTitle(BaseModel):
processing_status_union: (
ProcessingStatusDetail | ExtendedProcessingTask | ProcessingStatusTitle | None
) = Field('COMPLETED', title='Processing Status Union Title')
After:class ProcessingStatusUnionTitle(BaseModel):
__root__: (
ProcessingStatusDetail | ExtendedProcessingTask | ProcessingStatusTitle
) = Field(..., title='Processing Status Union Title')
class ProcessingTaskTitle(BaseModel):
processing_status_union: ProcessingStatusUnionTitle | None = Field(
default_factory=lambda: ProcessingStatusUnionTitle.parse_obj('COMPLETED'),
title='Processing Status Union Title',
)
--use-title-as-name is enabled - Arrays, dicts, enums-as-literals, and oneOf/anyOf unions that have a title in the schema now generate named type aliases or RootModel classes instead of being inlined. This improves readability but changes the generated type structure. For TypedDict output, generates type MyArrayName = list[str]. For Pydantic output, generates class MyArrayName(RootModel[list[str]]). (#2889)default_factory with a lambda that calls parse_obj() (Pydantic v1) or model_validate() (Pydantic v2) to construct the wrapper model. Code that introspects field defaults will see a factory function instead of a direct value. (#2889)$ref with nullable: true - When a JSON Schema property has a $ref combined with only nullable: true (and optionally metadata like title/description), the generator now uses the referenced type directly with Optional annotation instead of creating a new merged model. For example, a schema with multiple properties referencing User with nullable: true will now generate user_a: User | None instead of creating separate UserA, UserB model classes. This is a bug fix that reduces redundant model generation, but existing code that depends on the previously generated class names will break. (#2890)
Before:class UserA(BaseModel):
name: str
class UserB(BaseModel):
name: str
class Model(BaseModel):
user_a: UserA | None = None
user_b: UserB | None = None
After:class User(BaseModel):
name: str
class Model(BaseModel):
user_a: User | None = None
user_b: User | None = None
--use-title-as-name - When using --use-title-as-name, the generator now creates type aliases for additional cases: nested array items with titles, additionalProperties values with titles, oneOf/anyOf branches with titles, patternProperties, propertyNames, and primitive types with titles. Previously these were inlined; now they generate named type aliases. This is a bug fix per #2887, but changes generated output for schemas with titles on nested elements. (#2891)title is now excluded when merging with child schemas. This prevents unintended title inheritance that could affect model naming when --use-title-as-name is enabled. (#2891)allOf with single $ref no longer creates wrapper class - When a schema property uses allOf with only a single $ref and no additional properties, the generator now directly references the target type instead of creating an unnecessary wrapper class. This may affect code that depends on the previously generated wrapper class names or structure. For example, a property defined as allOf: [$ref: '#/components/schemas/ACHClass'] will now generate ach_class: ACHClass | None instead of creating an intermediate wrapper type. (#2902)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.51.0...0.52.0
Add deprecation warning for Pydantic v1 runtime by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2833
--input-model with Set, FrozenSet, Mapping, or Sequence types - When using --input-model to convert Pydantic models or dataclasses, types that were previously converted to list or dict are now preserved as their original Python types. For example, a field typed as Set[str] now generates set[str] instead of list[str], FrozenSet[T] generates frozenset[T], Mapping[K, V] generates Mapping[K, V] instead of dict[K, V], and Sequence[T] generates Sequence[T] instead of list[T]. This may cause type checking differences or runtime behavior changes if your code depended on the previous output types. (#2837)allOf with multiple $ref items where the child schema also defines properties that override parent properties will now generate classes with multiple inheritance (e.g., class Person(Thing, Location)) instead of a flattened single class with all properties merged inline. Previously, child property overrides were incorrectly treated as conflicts, triggering schema merging. Users relying on the flattened output may need to adjust their code. (#2838)
Before:class Person(BaseModel):
type: str | None = 'playground:Person'
name: constr(min_length=1) | None = None
address: constr(min_length=5)
age: int | None = None
After:class Thing(BaseModel):
type: str
name: constr(min_length=1)
class Location(BaseModel):
address: constr(min_length=5)
class Person(Thing, Location):
type: str | None = 'playground:Person'
name: constr(min_length=1) | None = None
age: int | None = None
ruff-check formatter, the --unsafe-fixes flag is now passed to ruff, which enables fixes that may change code behavior in potentially incorrect ways. This includes removing unused imports that might have side effects, removing unused variables that could affect debugging, and other transformations ruff considers "unsafe". Users who relied on the previous conservative safe-only fix behavior may see different generated code output. To restore the previous behavior, users can configure ruff via pyproject.toml or ruff.toml to disable specific unsafe rules. (#2847)--reuse-model (Pydantic v2 only), models that would previously generate as type aliases (ChildModel = ParentModel) now generate as explicit subclasses (class ChildModel(ParentModel): pass). This change improves type checker compatibility and maintains proper type identity, but may affect code that relied on type alias semantics or compared types directly. (#2853)
Before:ArmLeft = ArmRight
After:class ArmLeft(ArmRight):
pass
const values in anyOf/oneOf now generate Literal types instead of inferred base types - Previously, a const value like "MODE_2D" in an anyOf/oneOf schema would generate str type. Now it generates Literal["MODE_2D"]. This change affects type hints in generated models and may require updates to code that type-checks against the generated output. For example:# Before (v0.x)
map_view_mode: str = Field("MODE_2D", alias="mapViewMode", const=True)
apiVersion: str = Field('v1', const=True)
# After (this PR)
map_view_mode: Literal["MODE_2D"] = Field("MODE_2D", alias="mapViewMode", const=True)
apiVersion: Literal['v1'] = Field('v1', const=True)
This is a bug fix that makes the generated code more type-safe, but downstream code performing type comparisons or using isinstance(field, str) checks may need adjustment. (#2864)DataType class: is_frozen_set, is_mapping, and is_sequence. Custom Jinja2 templates that inspect DataType flags may need to be updated to handle these new type variations if they contain logic that depends on exhaustive type flag checks. (#2837)pydantic_v2/BaseModel.jinja2 template, you need to update it. The conditional block that generated type aliases ({% if base_class != "BaseModel" and ... %}{{ class_name }} = {{ base_class }}{% else %}...{% endif %}) has been removed. Templates should now always generate class declarations. (#2853)--input-model-ref-strategy reuse-foreign behavior changed - Previously, this strategy compared the source type family against the input model's family (e.g., if input was Pydantic, any non-Pydantic type like dataclass was considered "foreign" and reused). Now it compares against the output model's family. This means types that were previously imported/reused may now be regenerated, and vice versa. For example, when converting a Pydantic model containing a dataclass to TypedDict output, the dataclass was previously imported (it was "foreign" to Pydantic input), but now it will be regenerated (it's not the same family as TypedDict output). Enums are always reused regardless of output type. (#2854)generate() allowed passing both a config object and individual keyword arguments, with keyword arguments overriding config values. Now, providing both raises ValueError: "Cannot specify both 'config' and keyword arguments. Use one or the other." Users must choose one approach: either pass a GenerateConfig object or use keyword arguments, but not both. (#2874)# Before (worked): keyword args overrode config values
generate(input_=schema, config=config, output=some_path)
# After (raises ValueError): must use one or the other
# Option 1: Use config only (include output in config)
config = GenerateConfig(output=some_path, ...)
generate(input_=schema, config=config)
# Option 2: Use keyword args only
generate(input_=schema, output=some_path, ...)
Parser.__init__, JsonSchemaParser.__init__, OpenAPIParser.__init__, and GraphQLParser.__init__ now accept either a config: ParserConfig object OR keyword arguments via **options: Unpack[ParserConfigDict], but not both simultaneously. Passing both raises a ValueError. Existing code using only keyword arguments continues to work unchanged. (#2877)# Before: Could potentially mix config with kwargs (undefined behavior)
parser = JsonSchemaParser(source="{}", config=some_config, field_constraints=True)
# After: Raises ValueError - must use one approach or the other
parser = JsonSchemaParser(source="{}", config=some_config) # Use config object
# OR
parser = JsonSchemaParser(source="{}", field_constraints=True) # Use keyword args
Parser, JsonSchemaParser, OpenAPIParser, or GraphQLParser may need updates if they override __init__ and call super().__init__() with explicit parameter lists. The new signature uses **options: Unpack[ParserConfigDict] instead of explicit parameters. (#2877)Config.input_model type changed from str to list[str] - The input_model field in the Config class now stores a list of strings instead of a single string. While backward compatibility is maintained when setting the value (single strings are automatically coerced to lists), code that reads config.input_model will now receive a list[str] instead of str | None. Users who programmatically access this field should update their code to handle the list type. (#2881)# Before
if config.input_model:
process_model(config.input_model) # config.input_model was str
# After
if config.input_model:
for model in config.input_model: # config.input_model is now list[str]
process_model(model)
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.50.0...0.51.0
Models with unevaluatedProperties now generate extra field configuration - JSON Schemas containing unevaluatedProperties: false will now generate mode
unevaluatedProperties now generate extra field configuration - JSON Schemas containing unevaluatedProperties: false will now generate models with extra='forbid' (Pydantic v2) or extra = Extra.forbid (Pydantic v1), and schemas with unevaluatedProperties: true will generate extra='allow'. Previously this keyword was ignored. This may cause validation errors for data that was previously accepted. (#2797)
Example - a schema like:{
"title": "Resource",
"type": "object",
"properties": { "name": { "type": "string" } },
"unevaluatedProperties": false
}
Previously generated:class Resource(BaseModel):
name: str | None = None
Now generates:class Resource(BaseModel):
model_config = ConfigDict(extra='forbid')
name: str | None = None
utf-8 instead of the system's locale-preferred encoding (e.g., cp1252 on Windows). Users who rely on locale-specific encoding must now explicitly use --encoding to specify their desired encoding (#2802)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.49.0...0.50.0
Merge duplicate breaking change headings in release notes by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2776
SchemaParseError instead of Pydantic ValidationError - When parsing invalid schema data (e.g., "minimum": "not_a_number"), the library now raises SchemaParseError instead of passing through Pydantic's ValidationError. Users catching pydantic.ValidationError for schema validation failures should update to catch SchemaParseError. The original error is preserved in the original_error attribute. (#2786)--output is not specified - The --output argument has always documented (default: stdout) in --help, but previously no output was produced. Now works as documented. (#2787)generate() function now returns str | GeneratedModules | None instead of None - Existing code ignoring the return value is unaffected. (#2787)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.48.0...0.49.0
Non-lowercase forms (True, False, TRUE, FALSE) now emit a deprecation warning indicating future versions will only support lowercase true/false.
Custom class name generator now applied consistently during duplicate name resolution - Previously, when using custom_class_name_generator, the default PascalCase naming was incorrectly applied during duplicate name resolution. Now the custom generator is respected throughout, which may change generated class names. For example, a class name like nested_object_result with a custom generator f"Custom{name}" will now produce CustomNested_object_result instead of CustomNestedObjectResult. Users relying on the previous behavior should update their code to expect the new, correct class names. (#2757)
YAML 1.1 boolean keywords now preserved as strings in enums - Values like YES, NO, on, off, y, n that were previously converted to Python booleans are now preserved as their original string values. This fixes issues where string enum values were incorrectly converted but may change generated output for schemas that relied on the previous behavior. For example, a YAML enum with YES will now generate YES = 'YES' instead of being converted to True. (#2767)
true, false, True, False, TRUE, FALSE are now recognized as boolean values. YAML 1.1 boolean aliases (yes, no, on, off, y, n, etc.) are no longer parsed as booleans and will be treated as strings. Non-lowercase forms (True, False, TRUE, FALSE) now emit a deprecation warning indicating future versions will only support lowercase true/false. (#2767)Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.47.0...0.48.0
Add Python 3.13 deprecation warning documentation by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2743
RootModel defaults use direct instantiation - RootModel fields with default values now generate ClassName(value) instead of ClassName.model_validate(value). This produces cleaner code but changes the generated output (#2714)
--strict-nullable now applies to JSON Schema - The --strict-nullable option is no longer OpenAPI-only and has been moved to Field customization options. It now also correctly respects nullable on array items (#2713, #2727)
If you use custom Jinja2 templates that check field.nullable, you may need to update them. The nullable field on JsonSchemaObject now defaults to None instead of False. Templates should check field.nullable is True instead of just if field.nullable (#2715)
Example change:
{# Before #}
{%- if field.nullable %}...{% endif %}
{# After #}
{%- if field.nullable is true %}...{% endif %}
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.46.0...0.47.0
Python 3.9 support dropped - Minimum Python version is now 3.10+
list[...]/dict[...] are now used instead of List[...]/Dict[...]. Use --no-use-standard-collections to restore previous behavior (#2699)X | Y syntax is now used instead of Union[X, Y]/Optional[X]. Use --no-use-union-operator to restore previous behavior (#2703)required and nullable no longer get = None. The pydantic_v2/BaseModel.jinja2 template logic was updated to only assign default values when field.required is false. This fixes incorrect behavior where required fields could be omitted (#2520)--enum-field-as-literal setting instead of forcing all. Added new --enum-field-as-literal none option (#2691)prefixItems with matching minItems/maxItems and no items now generates tuple[T1, T2, ...] instead of list[...]. This applies when the array has a fixed length with heterogeneous types (#2537)str | None) by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2709Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.45.0...0.46.0
docs: add cross-links between CLI reference and usage documentation pages by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/26
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.44.0...0.45.0
Fix empty dict/list defaults not generating default_factory for Pydantic models by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/p
from __future__ import annotations for Python 3.14+ targets (PEP 649) by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2658Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.43.1...0.44.0
Add support for x-enumNames extension by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2653
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.43.0...0.43.1
Fix extra blank line after custom file header with future imports by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2638
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.42.2...0.43.0
Fix Python 3.9 compatibility regression in _scc.py by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2628
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.42.1...0.42.2
Add named profile support and --ignore-pyproject option for pyproject.toml configuration by @koxudaxi in https://github.com/koxudaxi/datamodel-code-ge
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.42.0...0.42.1
Improve type resolution for inherited fields in allOf with complex schemas by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2
If you use custom Jinja2 templates, you may need to update them to handle default_factory correctly with --use-annotated.
A new property field.has_default_factory_in_field has been added. Templates should check this property to avoid generating duplicate
default assignments when Field(default_factory=...) is used.
Example change in templates:
{# Before #}
{%- if not (field.required or ...) %} = {{ field.represented_default }}{% endif %}
{# After #}
{%- if not field.has_default_factory_in_field and not (field.required or ...) %} = {{ field.represented_default }}{% endif %}
Affected built-in templates:
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.41.0...0.42.0
Fix: resolve relative $ref correctly when fetching schemas from HTTP URLs by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/26
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.40.0...0.41.0
Fix invalid Union syntax when using --collapse-root-models by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2594
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.39.0...0.40.0
Add --all-exports-scope and --all-exports-collision-strategy options for recursive exports by @koxudaxi in https://github.com/koxudaxi/datamodel-code-
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.38.0...0.39.0
Fix transitive local reference resolution in external schema files by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2577
__all__ in __init__.py by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2586Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.37.0...0.38.0
Add PEP 257 docstrings to modules and test files by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2548
--generate-pyproject-config CLI option by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2551webhooks in --openapi-scopes by @HNygard in https://github.com/koxudaxi/datamodel-code-generator/pull/2481Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.36.0...0.37.0
OpenAPI byte-formatted string properties for Pydantic v2 are now generated as bytes fields that Pydantic automatically decodes from base64-encoded str
OpenAPI byte-formatted string properties for Pydantic v2 are now generated as bytes fields that Pydantic automatically decodes from base64-encoded strings at runtime. Code that relied on these fields being plain str values (the encoded representation) may need to be updated. by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2511 (closes https://github.com/koxudaxi/datamodel-code-generator/issues/189)
Enums inferred from OpenAPI / JSON Schema string or integer enums are now generated as specialized StrEnum / IntEnum subclasses by default when supported by the target Python version. This changes the base class of existing generated enums and can affect comparisons, JSON encoding, and downstream type checks. You can opt out using the --no-use-specialized-enum CLI flag or use_specialized_enum = false in the configuration file. by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2512 (closes https://github.com/koxudaxi/datamodel-code-generator/issues/1313 and https://github.com/koxudaxi/datamodel-code-generator/issues/2534)
For some Pydantic v2 collection schemas that previously generated a RootModel wrapper (for example the MyArray case described in https://github.com/koxudaxi/datamodel-code-generator/issues/1830), the generated code now uses a TypeAlias instead of a dedicated model class. Projects that import or subclass such wrapper models may need to adjust to use the alias instead. by @butvinm in https://github.com/koxudaxi/datamodel-code-generator/pull/2505 (closes https://github.com/koxudaxi/datamodel-code-generator/issues/1848, https://github.com/koxudaxi/datamodel-code-generator/issues/2018, https://github.com/koxudaxi/datamodel-code-generator/issues/2427, and https://github.com/koxudaxi/datamodel-code-generator/issues/2487)
byte in Pydantic v2 by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2511TYPE_CHECKING blocks by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2539null type by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2542Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.35.0...0.36.0
Add support to Python 3.14 by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2469
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.34.0...0.35.0
TypedDict: Add support for const fields using Literal by @erandagan in https://github.com/koxudaxi/datamodel-code-generator/pull/2475
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.33.0...0.34.0
Run the test suite daily to check breaking changes by @gaborbernat in https://github.com/koxudaxi/datamodel-code-generator/pull/2479
tmp_path fixture instead of TemporaryDirectory by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2463@model_validator() usage for Pydantic 2.12 by @ilovelinux in https://github.com/koxudaxi/datamodel-code-generator/pull/2472Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.32.0...0.33.0
modify __typename field to honor --use-default-kwarg flag by @rpmcginty in https://github.com/koxudaxi/datamodel-code-generator/pull/2420
--use-default-kwarg flag by @rpmcginty in https://github.com/koxudaxi/datamodel-code-generator/pull/2420Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.31.2...0.32.0
fix: prevent code injection through filename in generated headers by @koxudaxi in https://github.com/koxudaxi/datamodel-code-generator/pull/2428
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.31.1...0.31.2
fix: documentation for --allow-extra-fields by @cosmo-grant in https://github.com/koxudaxi/datamodel-code-generator/pull/2416
--extra-fields option in pydantic v2 models by @cosmo-grant in https://github.com/koxudaxi/datamodel-code-generator/pull/2423Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.31.0...0.31.1
Resolve capitalize-enum-member not working with use-subclass-enum and snake-case-field when typed enum by @kevin-paulson-mindbridge-ai in https://gith
--extra-fields option to allow, forbid, or ignore extra fields by @cosmo-grant in https://github.com/koxudaxi/datamodel-code-generator/pull/2417Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.30.2...0.31.0
[pre-commit.ci] pre-commit autoupdate by @pre-commit-ci in https://github.com/koxudaxi/datamodel-code-generator/pull/2393
coerce_numbers_to_str in ConfigDict by @robotadam in https://github.com/koxudaxi/datamodel-code-generator/pull/2394--frozen-dataclasses flag to generate frozen dataclasses by @K-dash in https://github.com/koxudaxi/datamodel-code-generator/pull/2408Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.30.1...0.30.2
fix: TypeError: '<' not supported between instances of 'str' and 'NoneType' by @gjcarneiro in https://github.com/koxudaxi/datamodel-code-generator/pul
Full Changelog: https://github.com/koxudaxi/datamodel-code-generator/compare/0.30.0...0.30.1
One column per quarter.