Skip to content

Commit

Permalink
Merge pull request #36 from mathieu-gillot/feat/handle-model-construct
Browse files Browse the repository at this point in the history
feat(model_construct): handle partially hydrated models
  • Loading branch information
ddanier committed Sep 17, 2024
2 parents 4af2851 + e536323 commit 168b595
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pydantic_changedetect/changedetect.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def model_changed_fields(self) -> Set[str]:

changed_fields = self.model_self_changed_fields.copy()
for field_name, model_field in self_compat.model_fields.items():
# Support for instances created through model_construct, when not all fields have been defined
if field_name not in self.__dict__:
continue

field_value = self.__dict__[field_name]

# Value is a ChangeDetectionMixin instance itself
Expand Down
16 changes: 16 additions & 0 deletions tests/test_changedetect.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ class Something(ChangeDetectionMixin, pydantic.BaseModel):
id: int


class SomethingMultipleFields(ChangeDetectionMixin, pydantic.BaseModel):
id: int
foo: str


class Unsupported(pydantic.BaseModel):
id: int

Expand Down Expand Up @@ -479,6 +484,17 @@ def test_model_construct_works():
assert something.model_has_changed is True


@pytest.mark.skipif(PYDANTIC_V1, reason="pydantic v1 does not support model_construct()")
def test_model_construct_works_for_models_loaded_with_few_fields():
something_multiple_fields = SomethingMultipleFields.model_construct(id=1)

assert something_multiple_fields.model_has_changed is False

something_multiple_fields.id = 2

assert something_multiple_fields.model_has_changed is True


@pytest.mark.skipif(PYDANTIC_V1, reason="pydantic v1 does not trigger warnings")
def test_construct_works_on_v2():
with pytest.warns(DeprecationWarning):
Expand Down

0 comments on commit 168b595

Please sign in to comment.