gnikit
gnikit

Reputation: 1291

Pydantic add descriptions to dynamic model

I was wondering if there is a way to assign description when creating a model dynamically. The static equivalent would be

from pydantic import BaseModel, Field, create_model

class MainModel(BaseModel):
    value1: int = Field(-1, description="desc1")
    value2: int = Field(-2, description="desc2")

print(MainModel.schema_json(indent=2))

Dynamically, what I have so far is

from pydantic import create_model

attrs = {"value1": -1, "value2": -2}
m = create_model("MainModel", **attrs)
print(m.schema_json(indent=2))

Is there a way to include the description field for the individual attributes?


Related post: Pydantic dynamic model creation with json description attribute

Upvotes: 2

Views: 1481

Answers (1)

python_user
python_user

Reputation: 7123

Not sure if this is what you want, but if does give a similar JSON to what your static equivalent does. Look into FieldInfo.

from pydantic import create_model
from pydantic.fields import FieldInfo


attrs = {
    "value1": (int, FieldInfo(-1, description="desc1")),
    "value2": (int, FieldInfo(-2, description="desc2")),
}
m = create_model("MainModel", **attrs)

print(m.schema_json(indent=2))

That gives the following JSON

{
  "title": "MainModel",
  "type": "object",
  "properties": {
    "value1": {
      "title": "Value1",
      "description": "desc1",
      "default": -1,
      "type": "integer"
    },
    "value2": {
      "title": "Value2",
      "description": "desc2",
      "default": -2,
      "type": "integer"
    }
  }
}

Actually, this also seems to give the same output, I do not use this library much so I am not sure how they differ.

attrs = {
    "value1": Field(-1, description="desc1"),
    "value2": Field(-2, description="desc2"),
}

Upvotes: 1

Related Questions