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