Skip to content

Dynamic generation NameError with AliasChoices + Fields #2989

@jbmoorhouse

Description

@jbmoorhouse

Describe the bug
Field import statement is missing when aliases is used in conjunction with a schema that has required fields when creating models dynamically

To Reproduce

from datamodel_code_generator import GenerateConfig, generate_dynamic_models
from datamodel_code_generator.enums import DataModelType

"""Generate dynamic models based on the schema"""
schema = {
    "type": "object",
    "properties": {"name": {"type": "string"}},
    "required": ["name"], # Works when this is removed
}
config = GenerateConfig(
    class_name="Customer",
    output_model_type=DataModelType.PydanticV2BaseModel,
    aliases={"name": ["full_name", "customer_name"]},
)

models = generate_dynamic_models(schema, config=config)

Expected behavior
Should generate model

Actual Behaviour

exec(code, namespace)  # noqa: S102
    ^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 10, in <module>
  File "<string>", line 11, in Customer
NameError: name 'Field' is not defined

Version:

  • OS: Ubuntu 25.10
  • Python version: 3.11.14
  • datamodel-code-generator version: 0.53.0

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions