Pydantic field JSON alias simply does not work

Viewed 1703

I need to specify a JSON alias for a Pydantic object. It simply does not work.

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))

The output for this is {"for" : null instead of {"for" : "2"}

Is this real? How can such a simple use case not work?

1 Answers

You need to use the alias for object initialization. ComplexObject(for=str(x * y)) However for cannot be used like this in python, because it indicates a loop! You can use it like this : co = ComplexObject(**{"for": str(x * y)})

Related