Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 8 additions & 16 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -984,25 +984,17 @@ def sqlmodel_update(
obj: builtins.dict[str, Any] | BaseModel,
*,
update: builtins.dict[str, Any] | None = None,
**model_dump_kwargs,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kwargs will not give autocompletion, and it's error-prone

) -> _TSQLModel:
use_update = (update or {}).copy()
if isinstance(obj, dict):
for key, value in {**obj, **use_update}.items():
if key in get_model_fields(self):
setattr(self, key, value)
elif isinstance(obj, BaseModel):
for key in get_model_fields(obj):
if key in use_update:
value = use_update.pop(key)
else:
value = getattr(obj, key)
setattr(self, key, value)
for remaining_key, value in use_update.items():
if remaining_key in get_model_fields(self):
setattr(self, remaining_key, value)
else:
if not (isinstance(obj, dict) or isinstance(obj, BaseModel)):
raise ValueError(
"Can't use sqlmodel_update() with something that "
f"is not a dict or SQLModel or Pydantic model: {obj}"
)
if isinstance(obj, BaseModel):
obj = obj.model_dump(**model_dump_kwargs)
Comment on lines +1011 to +1024
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will break use cases with models that have fields with exclude=True:

from sqlmodel import Field, SQLModel


class Item(SQLModel):
    id: str
    param: str = Field(exclude=True)


a = Item.model_validate({"id": "1", "param": "1"})
b = Item.model_validate({"id": "1", "param": "2"})


a.sqlmodel_update(b, exclude={"id"})
# a.sqlmodel_update(b)


assert a.param == "2"

.. and probably some other cases when model has settings that change the default serialization schema.

use_update = (update or {}).copy()
for key, value in {**obj, **use_update}.items():
if key in get_model_fields(self):
setattr(self, key, value)
return self
12 changes: 12 additions & 0 deletions tests/test_update.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from pytest import raises
from sqlmodel import Field, SQLModel


def test_sqlmodel_update():
class Organization(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
name: str
city: str
headquarters: str

class OrganizationUpdate(SQLModel):
name: str
city: str | None = None

org = Organization(name="Example Org", city="New York", headquarters="NYC HQ")
org_in = OrganizationUpdate(name="Updated org")
Expand All @@ -17,4 +20,13 @@ class OrganizationUpdate(SQLModel):
update={
"headquarters": "-", # This field is in Organization, but not in OrganizationUpdate
},
exclude_unset=True,
)
# fields that should stay the same
assert org.city == "New York"
# fields that should be updated
assert org.name == "Updated org"
assert org.headquarters == "-"
# test raise value error when passing in updates other than dict or BaseModel
with raises(ValueError):
org.sqlmodel_update(["Boston"])
Loading