The --aliases option allows you to rename fields in the generated models. This is useful when you want to use different Python field names than those defined in the schema while preserving the original names as serialization aliases.
datamodel-codegen \
--input schema.json \
--output-model-type pydantic_v2.BaseModel \
--output model.py \
--aliases aliases.jsonThe alias file is a JSON file that maps original field names to their Python aliases.
The simplest format applies aliases to all fields with the matching name, regardless of which class they belong to:
{
"id": "id_",
"type": "type_",
"class": "class_"
}This will rename all fields named id to id_, all fields named type to type_, etc.
When you have the same field name in multiple classes but want different aliases for each, use the scoped format with ClassName.field:
{
"User.name": "user_name",
"Address.name": "address_name",
"name": "default_name"
}⚡ Priority: Scoped aliases take priority over flat aliases. In the example above:
User.namewill be renamed touser_nameAddress.namewill be renamed toaddress_name- Any other class with a
namefield will usedefault_name
{
"type": "object",
"title": "Root",
"properties": {
"name": {"type": "string"},
"user": {
"type": "object",
"title": "User",
"properties": {
"name": {"type": "string"},
"id": {"type": "integer"}
}
},
"address": {
"type": "object",
"title": "Address",
"properties": {
"name": {"type": "string"},
"city": {"type": "string"}
}
}
}
}{
"Root.name": "root_name",
"User.name": "user_name",
"Address.name": "address_name"
}from pydantic import BaseModel, Field
class User(BaseModel):
user_name: str | None = Field(None, alias='name')
id: int | None = None
class Address(BaseModel):
address_name: str | None = Field(None, alias='name')
city: str | None = None
class Root(BaseModel):
root_name: str | None = Field(None, alias='name')
user: User | None = None
address: Address | None = None- The
ClassNamein scoped format must match the generated Python class name (after title conversion) - When using
--use-title-as-name, the class name is derived from thetitleproperty in the schema - Aliases are applied during code generation, so the original field names are preserved as Pydantic
aliasvalues for proper serialization/deserialization
- 🖥️ CLI Reference:
--aliases- Detailed CLI option documentation with examples