How to fix - UserWarning: Pydantic serializer warnings in Pydantic V2?
Asked Answered
H

2

6

Using datamodel-codegen command with JSON data as input type and generating Pydantic schema as output, during this process I was seeing warnings.

What is the meaning of these warnings and how to fix them? What kind of issues it can create(or why this is a warning)?

UserWarning:

Expected `Union[list[definition-ref], definition-ref, bool]` but got `JsonSchemaObject` - serialized value may not be as expected
Expected `Union[definition-ref, bool]` but got `JsonSchemaObject` - serialized value may not be as expected
Expected `Union[definition-ref, bool]` but got `JsonSchemaObject` - serialized value may not be as expected
Expected `Union[definition-ref, bool]` but got `JsonSchemaObject` - serialized value may not be as expected
  return self.__pydantic_serializer__.to_python(

To reproduce:

pets.json

{
  "pets": [
    {
      "name": "dog",
      "age": 2
    },
    {
      "name": "cat",
      "age": 1
    },
    {
      "name": "snake",
      "age": 3,
      "nickname": "python"
    }
  ],
  "status": 200
}

Command:

datamodel-codegen  --input pets.json --input-file-type json --output model.py

Versions:

python - 3.11.4
pydantic==2.1.1
datamodel-code-generator==0.21.4
genson==1.2.2
Havelock answered 11/8, 2023 at 6:16 Comment(0)
O
0

I had a similar issue when there are cyclic nested models. If that is your problem, you need to call:

YourSchemaContainingNestedModel.model_rebuild()

after declaring the model.

Not sure if this is your case, though, since I cannot see the schemas you are using.

Osiris answered 6/9, 2023 at 16:13 Comment(1)
To reproduce, you can follow the steps mentioned in the post. In my case, I am passing JSON data(not JSON Schema) as input and getting the Pydantic schema as output. So, this solution won't work.Havelock
H
0

In my case updating pydantic and datamodel-code-generator helped

pip install -U pydantic datamodel-code-generator

For python 3.10

Homeward answered 2/11, 2023 at 8:25 Comment(2)
Can you mention the versions of pydantic, datamodel-code-generator?Havelock
pydantic==2.4.2 datamodel-code-generator==0.22.1Homeward

© 2022 - 2024 — McMap. All rights reserved.