Why sqlmodel_update method don't ignore the None fields automatically?
#1680
Replies: 1 comment
-
|
{}means “do not change {"age": null}means “explicitly clear
HeroUpdate() # -> {}
HeroUpdate(age=None) # -> {"age": None}
HeroUpdate(age=42) # -> {"age": 42}
hero_data = hero.model_dump(exclude_unset=True)
db_hero.sqlmodel_update(hero_data)This is intentional and is documented in SQLModel's Update Data with FastAPI section: an explicitly supplied If your API contract says that hero_data = hero.model_dump(
exclude_unset=True,
exclude_none=True,
)
db_hero.sqlmodel_update(hero_data)It should not be the global default because that version makes it impossible for the client to clear Passing the model directly is supported by the method's type signature: db_hero.sqlmodel_update(hero)but it is not equivalent for PATCH. The current implementation iterates every field of a model argument, including fields that were omitted and received their default Regarding static checking: a partial update is intrinsically dynamic — its keys are determined by the JSON request at runtime — so a type checker cannot prove the exact dictionary shape after def apply_hero_patch(target: Hero, patch: HeroUpdate) -> None:
if "name" in patch.model_fields_set and patch.name is not None:
target.name = patch.name
if "secret_name" in patch.model_fields_set and patch.secret_name is not None:
target.secret_name = patch.secret_name
if "age" in patch.model_fields_set:
# None is intentionally allowed here to clear the database value.
target.age = patch.ageThat is more verbose, but it retains autocomplete and makes each field's If this clarifies why |
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
To use the db_hero.sqlmodel_update method when a field has a None value, it is currently necessary to convert the typed BaseModel object into an untyped dictionary before updating it:
However, converting the model to a dictionary removes static analysis and autocompletion. The codebase would be more concise and safer if the sqlmodel_update method could automatically ignore None fields.
Operating System
Linux
Operating System Details
OS: Ubuntu 24.04.3 LTS x86_64
Host: 550XDA P23CFB
Kernel: 6.14.0-37-generic
Shell: zsh 5.9
Resolution: 1920x1080
DE: GNOME 46.0
CPU: 11th Gen Intel i7-1165G7 (8) @ 4.700GHz
GPU: Intel TigerLake-LP GT2 [Iris Xe Graphics]
Memory: 10625MiB / 15716MiB
SQLModel Version
0.0.27
Python Version
3.12.3
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions