[Python] Pydantic "Input should be a valid string" when constructing with dictionary

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    This is the beginning of the class code, the dictionary I am using to construct the class, and the lines where the code fails.

    from beanie import Document
    from pydantic import Field, ConfigDict, field_validator
    class Schema(Document):
    model_config = ConfigDict(extra='forbid')
    name: str = Field(alias='name')
    description: str = Field(alias='description')
    date: int = Field(alias='date')


    def get_default_schema():
    schema_dict = {
    'name': 'schema_name',
    'description': 'my description',
    'date': 2022
    }
    return schema_dict


    schema_dict = get_default_schema()
    sch = Schema(**schema_dict)


    This is the error pydantic returns

    self = Schema(), args = ()
    kwargs = {'date': 2022, 'description': 'my description', 'name': 'schema_name'}

    def __init__(self, *args: Any, **kwargs: Any) -> None:
    > super(Document, self).__init__(*args, **kwargs)
    E pydantic_core._pydantic_core.ValidationError: 2 validation errors for Schema
    E description
    E Input should be a valid string [type=string_type, input_value=None, input_type=NoneType]
    E For further information visit https://errors.pydantic.dev/2.10/v/string_type
    E date
    E Input should be a valid integer [type=int_type, input_value=None, input_type=NoneType]
    E For further information visit https://errors.pydantic.dev/2.10/v/int_type


    All of the data types are specified correctly in the class and the dictionary, and I have an example file of this kind of class construction that functions perfectly fine. It seems like pydantic isn't recognizing 2 out of the 3 attributes for some reason. Maybe I'm just missing something obvious.

    Continue reading...

Compartilhe esta Página