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 badges1 Answer
Reset to default 2This 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
.