Hyperion icon indicating copy to clipboard operation
Hyperion copied to clipboard

Calling patch with no changes will fail

Open armanddidierjean opened this issue 1 year ago • 1 comments

Subject of the issue

If we call an update crud without providing any change, an error will be thrown.

Proposed solution

    if not any(recommendation.model_dump().values()):
        return

    result = await db.execute(
        update(models_recommendation.Recommendation)
        .where(models_recommendation.Recommendation.id == recommendation_id)
        .values(**recommendation.model_dump(exclude_none=True))
    )
    if result.rowcount == 1:
        await db.commit()
    else:
        await db.rollback()
        raise ValueError

See @julien4215 comment

armanddidierjean avatar Mar 02 '24 12:03 armanddidierjean

Its seems the proposed solution does not work if some fields are set to False.

According to https://github.com/pydantic/pydantic/discussions/4613 we could use:

if not bool(
    recommendation.model_fields_set
):

If we need to exclude some fields from the model, we can use recommendation.model_fields_set - {"field_to_remove"},

armanddidierjean avatar Aug 22 '24 13:08 armanddidierjean