最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Field validator not called on SQLModel - Stack Overflow

programmeradmin0浏览0评论

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)
    sessionmit()
    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.

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)
    sessionmit()
    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.

Share edited Mar 7 at 13:57 Daniel Walker asked Mar 6 at 20:06 Daniel WalkerDaniel Walker 6,8247 gold badges24 silver badges62 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

This is one of the oldest issues with SQLModel (see e.g. this github issue from 2022). Validators are not called on models with table=True.

发布评论

评论列表(0)

  1. 暂无评论