BUG: SQLModels with table=True aren't properly restored from JSON #1791
Replies: 2 comments
-
|
This is a known limitation, but it's not clearly documented yet. You should NOT use table-models for validation. You should create separate model for validation (use inheritance to reduce code duplication) as shown in https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance |
Beta Was this translation helpful? Give feedback.
-
|
This really should be documented (or fixed, is there a good reason for this or is it just a bug?), this has cost me (and probably others) days to figure out, it's not obvious at all. Also note how https://sqlmodel.tiangolo.com/tutorial/fastapi/simple-hero-api/#create-heroes-path-operation implies that using table-models with FastAPI is fine - that's extremely misleading (even if it might work in that particular case because all involved types can be natively represented by JSON). The tutorial you linked suggests using inheritance when having additional fields in the table model that aren't needed (or shouldn't be) in the the other one (the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Basically: For SQLModels with
table=True,model_validate_json(jstr)is broken, and so ismodel_validate( json.loads(jstr) ), but in slightly different ways.model_validate_json(jstr)does not restore non-JSON types (meaning, ones not natively supported by JSON) properly when used with atable=TrueSQLModel.For example, serialized
UUIDanddatetimeobjects remain strings.model_validate( json.loads(jstr) )does restore those types properly when used directly on an SQLModeltable=Truetype, but when that SQLModel is a member of another type it's broken in the same way as the former case (e.g. UUIDs remain strings).Weirdly, for SQLModels with table=False everything seems to work.
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.37
Python Version
3.13.9
Additional Context
Of course this issue also creates problems when using affected types with FastAPI.
The output when running the aforementioned code looks like this:
Details
Beta Was this translation helpful? Give feedback.
All reactions