Repository navigation
First Check
Example Codefrom sqlmodel import SQLModel
class HeroUpdate(SQLModel):
name: str | None = None
age: int | None = None
update = HeroUpdate(name="Spider-Man")
update_data = update.model_dump(exclude_unset=True)
print(update_data)DescriptionI'm working on a FastAPI project using SQLModel and I'm trying to implement a PATCH endpoint. I want to update only the fields provided in the request without overwriting the existing values with defaults or None. What is the recommended way to do this using SQLModel? Is model_dump(exclude_unset=True) the correct approach, or is there a better alternative? Operating SystemWindows Operating System Detailswindows 11 Project Versionnot sure Python Version3.14.8 Additional ContextNo response |
Replies: 1 comment
|
Yes, You can combine it with @app.patch("/heroes/{hero_id}")
def update_hero(
hero_id: int,
hero_update: HeroUpdate,
session: Session = Depends(get_session)
):
db_hero = session.get(Hero, hero_id)
if not db_hero:
raise HTTPException(status_code=404, detail="Hero not found")
update_data = hero_update.model_dump(exclude_unset=True)
db_hero.sqlmodel_update(update_data)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
This means existing database values remain unchanged when a field is omitted from the PATCH request. If a field is explicitly provided as |
Yes,
model_dump(exclude_unset=True)is the recommended approach for implementing partial updates with SQLModel.You can combine it with
sqlmodel_update():exclude_unset=Trueensures that only fields explicitly provided by …