sqlmodel_update() overwrites all fields from BaseModel input, silently destroying data in PATCH endpoints #1838
Unanswered
mahdirajaee
asked this question in
Questions
Replies: 1 comment
-
|
@mahdirajaee, please follow rules - don't open issues, start discussion instead |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
When
sqlmodel_update()receives aBaseModelinstance, it iterates over every field and callssetattrfor each one — including fields the caller never set. There is noexclude_unsetparameter and no awareness of__pydantic_fields_set__.Reproduction
Client sends
{"name": "New Name"}.hero_update.agedefaults toNone. The method overwrites the hero's existingagewithNone, silently destroying data.Current Workaround
This works but is non-obvious. The method's type signature explicitly accepts
BaseModel, implying it handles this case correctly.Proposed Fix
Add an
exclude_unset: bool = Falseparameter tosqlmodel_update(). WhenTrueandobjis aBaseModel, filter to onlyobj.__pydantic_fields_set__before applying:This is the single most common FastAPI + SQLModel pattern and the silent data corruption is a significant footgun.
Beta Was this translation helpful? Give feedback.
All reactions