是否可以使用Pydantic来序列化父对象之间的大型共享对象?
例如,在这段代码中:
from typing import List, Optional
from pydantic import BaseModel
class Child(BaseModel):
description: str
class Parent(BaseModel):
id: int
large: Optional[Child] = None
external_data = {
'id': '123',
'signup_ts': '2019-06-01 12:22',
'friends': [1, 2, '3'],
}
c1 = Child(description="THIS IS A VERY LONG DESCRIPTION THAT I ONLY WANT TO WRITE ONCE")
p1 = Parent(id=123, large=c1)
p2 = Parent(id=456, large=c1)
class ParentList(BaseModel):
list: List[Parent]
print(ParentList(list=[p1, p2]).json(indent=4))
输出将是
{
"list": [
{
"id": 123,
"large": {
"description": "THIS IS A VERY LONG DESCRIPTION THAT I ONLY WANT TO WRITE ONCE"
}
},
{
"id": 456,
"large": {
"description": "THIS IS A VERY LONG DESCRIPTION THAT I ONLY WANT TO WRITE ONCE"
}
}
]
}
假设大字段非常大,我只想表示一次。
我想象的输出是这样的:
{
"child": {
"1": {
"id": "1",
"description": "THIS IS A VERY LONG DESCRIPTION THAT I ONLY WANT TO WRITE ONCE"
}
},
"parent": {
"123": {
"id": "123",
"large": "1"
},
"456": {
"id": "456",
"large": "1"
}
}
}
有一个JS库可以做类似的事情,叫做Normalizr。
这是Pydantic内置的吗?它很难实现还是超出了库的范围?
从pydantic的BaseModel
重写json()
可能是您正在寻找的解决方案。
https://pydantic-docs.helpmanual.io/usage/exporting_models/modeljson