[Python] Field validator not called on SQLModel

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI setup of the form:

    class Foo(sqlmodel.SQLModel, table=True):
    id: typing.Optional[int] = sqlmodel.Field(primary_key=True)
    data: str

    @pydantic.field_validator("data", mode="before")
    def serialize_dict(cls, value):
    if isinstance(value, dict):
    return json.dumps(value)
    return value


    @app.post("/foos")
    def create_foo(foo: Foo, session: sqlmodel.Session = fastapi.Depends(get_session)):
    session.add(foo)
    session.commit()
    return fastapi.Response()


    I then POST

    {
    "data": {
    "bar": 5
    }
    }


    to /foos. However, this is throwing a SQL exception because the data value couldn't be bound. After putting in some logging statements, I discovered that foo.data is a dict and not a str. In addition, I confirmed that my validator is never called.

    Since SQLModel inherits from pydantic.BaseModel, I would have thought I could use such a validator. What am I missing?

    This is sqlmodel 0.0.23 with pydantic 2.10.6.

    Continue reading...

Compartilhe esta Página