🔒 Field Constraints¶
The --field-constraints option converts all con* annotations (like conint, constr) to Field constraint options.
🤔 Why use this?¶
Mypy may show errors for con* annotations on fields. The --field-constraints option resolves this problem by using standard Field() constraints instead.
📝 Example¶
Convert simple JSON Schema model.json to pydantic model model.py:
model.json
{
"type": "object",
"properties": {
"name": {
"type": "string",
"maxLength": 64
}
},
"required": ["name"]
}
❌ Without --field-constraints option¶
datamodel-codegen --input model.json --input-file-type jsonschema --output-model-type pydantic_v2.BaseModel > model.py
Generated model.py
# generated by datamodel-codegen:
# filename: model.json
# timestamp: 2020-07-20T15:37:56+00:00
from __future__ import annotations
from pydantic import BaseModel, constr
class Model(BaseModel):
name: constr(max_length=64)
🔴 Run mypy...
$ mypy model.py
model.py:3: error: Invalid type comment or annotation
model.py:3: note: Suggestion: use constr[...] instead of constr(...)
Found 1 error in 1 file (checked 1 source file)
mypy shows errors! 😱
✅ With --field-constraints option¶
datamodel-codegen \
--input model.json \
--input-file-type jsonschema \
--output-model-type pydantic_v2.BaseModel \
--use-annotated \
--field-constraints \
> model.py
Generated model.py
# generated by datamodel-codegen:
# filename: model.json
# timestamp: 2020-07-20T15:47:21+00:00
from __future__ import annotations
from typing import Annotated
from pydantic import BaseModel, Field
class Model(BaseModel):
name: Annotated[str, Field(max_length=64)]
🟢 Run mypy...
No errors! 🎉
📖 See Also¶
- 🖥️ CLI Reference:
--field-constraints- Detailed CLI option documentation with examples - 🔁 Type Mappings - Override schema types before field constraints are applied