我有以下两个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]
当我在JobTaskSettings
上调用.dict
Doc时,我希望得到以下结果
{
"libraries": [
{
"pypi": {
"package": "requests"
}
},
{
"pypi": {
"package": "bs4"
}
}
]
}
Where to每个库模型都用"pypi"关键。这可能吗?
您只需要再添加一个类并修改Library类:
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)
和输出:
>>> my_instance.json()
{
"libraries": [
{
"pypi": {
"package": "requests"
}
},
{
"pypi": {
"package": "bs4"
}
}
]
}
这比更改.dict()或.json()行为更安全