Skip to content
Discussion options

You must be logged in to vote

Yes, model_dump(exclude_unset=True) is the recommended approach for implementing partial updates with SQLModel.

You can combine it with sqlmodel_update():

@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

exclude_unset=True ensures that only fields explicitly provided by …

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by we4r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
2 participants