我想使用 Pydantic 2 将数据导出到 Kafka 子队列,并且需要在不同的模型中导出到 JSON。
例如我有以下对象:
class obj(BaseModel):
resource: str
resourceid: int
resourceTime: datetime
name: str
option1: str
option2: int
{
"resource": "TEST",
"resourceid": "1234",
"resourceTime": "2024-09-03 00:00:00",
"option1": "test",
"option2": 23421,
"name": "test"
}
但是我需要这样转储:
{
"resource": "TEST",
"name": "test,
"resourceid": "1234",
"resourceTime": "2024-09-03 00:00:00",
"attributes": [
{
"name": "option1",
"value": "test",
},
{
"name": "option2",
"value": 23421
},
{
"name": "name",
"value": "test"
}
]
}
有可能使用 Pydantic 的某些功能来实现这一点吗?
谢谢。
您可以使用
model_serializer
:
from datetime import datetime
from pydantic import BaseModel, model_serializer
class obj(BaseModel):
resource: str
resourceid: int
resourceTime: datetime
name: str
option1: str
option2: int
@model_serializer(mode="wrap")
def _serialize(self, handler):
d = handler(self)
d["resourceid"] = str(d["resourceid"])
del d["option1"]
del d["option2"]
d["attributes"] = [
{
"name": "option1",
"value": self.option1
},
{
"name": "option2",
"value": self.option2
},
{
"name": "name",
"value": self.name
},
]
return d
o = obj.model_validate(
{
"resource": "TEST",
"resourceid": "1234",
"resourceTime": "2024-09-03 00:00:00",
"option1": "test",
"option2": 23421,
"name": "test"
}
)
print(o.model_dump())