python Pydantic字段JSON别名根本不起作用

yhuiod9q  于 2022-10-30  发布在  Python
关注(0)|答案(2)|浏览(170)

我需要为一个Pydantic对象指定一个JSON别名。它根本不起作用。

from pydantic import Field
from pydantic.main import BaseModel

class ComplexObject(BaseModel):
    for0: str = Field(None, alias="for")

def create(x: int, y: int):
    print("was here")
    co = ComplexObject(for0=str(x * y))
    return co

co = create(x=1, y=2)
print(co.json(by_alias=True))

此操作的输出为{"for" : null,而不是{"for" : "2"}
这是真实的的吗?这么简单的用例怎么会不起作用呢?

tsm1rwdh

tsm1rwdh1#

你需要使用别名来初始化对象。ComplexObject(for=str(x * y))但是for在python中不能这样使用,因为它表示一个循环!你可以这样使用它:co = ComplexObject(**{"for": str(x * y)})

a8jjtwal

a8jjtwal2#

您可以将allow_population_by_field_name=True值添加到pydantic模型的Config上。

>>> class ComplexObject(BaseModel):
...     class Config:
...         allow_population_by_field_name = True
...     for0: str = Field(None, alias="for")
...
>>>
>>> def create(x: int, y: int):
...     print("was here")
...     co = ComplexObject(for0=str(x * y))
...     return co
...
>>>
>>> co = create(x=1, y=2)
was here
>>> print(co.json(by_alias=True))
{"for": "2"}
>>> co.json()
'{"for0": "2"}'
>>> co.json(by_alias=False)
'{"for0": "2"}'
>>> ComplexObject.parse_raw('{"for": "xyz"}')
ComplexObject(for0='xyz')
>>> ComplexObject.parse_raw('{"for": "xyz"}').json(by_alias=True)
'{"for": "xyz"}'
>>> ComplexObject.parse_raw('{"for0": "xyz"}').json(by_alias=True)
'{"for": "xyz"}'

相关问题