Skip to content

Field Constraints

An option --field-constraints converts all con* annotations to Field constraint options.

Mypy may show error for con* annotations on fields. The option resolves the problem.

Example

Convert simple JSON Schema model.json to pydantic model model.py

Input JSON Schema

model.json

{
  "type":  "object",
  "properties": {
    "name": {
      "type": "string",
      "maxLength": 64
    }
  },
  "required": ["name"]
}

Without --field-constraints option

$ datamodel-codegen --input a.json --input-file-type jsonschema > model.py 

Generated Model

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 show errors...

With --field-constraints option

$ datamodel-codegen --input model.json --input-file-type jsonschema --field-constraints > model.py 

Generated Model

model.py

# generated by datamodel-codegen:
#   filename:  model.json
#   timestamp: 2020-07-20T15:47:21+00:00

from __future__ import annotations

from pydantic import BaseModel, Field


class Model(BaseModel):
    name: str = Field(..., max_length=64)

Run mypy...

$ mypy model.py 
Success: no issues found in 1 source file

https://github.com/samuelcolvin/pydantic/issues/156