Tizianoreica
Tizianoreica

Reputation: 2236

How change .dict behavior in Pydantic for including an extra deep field

I have the two followings Class

class Library(BaseModel):
    package: str

class JobTaskSettings(TaskKey):
    description: Optional[str]
    depends_on: Optional[List[TaskKey]]
    on_cluster_id: str = Field(..., alias="existing_cluster_id")
    libraries: List[Library]

when I call .dict Doc on JobTaskSettings, I would like to have the following result

{
  "libraries": [
    {
      "pypi": {
        "package": "requests"
      }
    },
    {
      "pypi": {
        "package": "bs4"
      }
    }
  ]
}

Where to each Library Model is wrapped around another json Object with the "pypi" key. Is this possible?

Upvotes: 1

Views: 1255

Answers (1)

JacekK
JacekK

Reputation: 793

All you need is only add one more class and modifi Library class:

from pydantic import BaseModel
from typing import List


class Package(BaseModel):
    package: str


class Library(BaseModel):
    pypi: Package


class JobTaskSettings(BaseModel):
    libraries: List[Library]


package_1 = Package(package="requests")
package_2 = Package(package="bs4")
libraries = [Library(pypi=package_1), Library(pypi=package_2)]

my_instance = JobTaskSettings(libraries=libraries)

and the output:

>>> my_instance.json()
{
    "libraries": [
        {
            "pypi": {
                "package": "requests"
            }
        },
        {
            "pypi": {
                "package": "bs4"
            }
        }
    ]
}

This is more safe than changing .dict() or .json() bechaviour

Upvotes: 1

Related Questions