art049 / art049/odmantic

Using Model.model_construct breaks attr setters

Open
#486 0 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Python
Stars
1.2k
Forks
97
PR merge metrics
No merged PRs in 30d

Description

# Bug

Attempting to create a model instance using `Model.model_construct` results in `__fields_modified__` not being present on the instance, causing AttributeErrors to be raised later when attempting to set attributes on the instance.

### Current Behavior

```
#!/usr/bin/env python3
from datetime import time

# from pydantic import BaseModel
from odmantic import Model

class Test(Model):
foo: time

t = Test(foo=time(1, 2, 3))

print(t)
t.foo = time(4, 5, 6)

print(t)

obj = t.model_dump()
print(obj)

u = Test.model_construct(**obj)
# u = Test(**obj)

print(u)

u.foo = time(0, 9, 8) # raises AttributeError
print(u)
```

### Expected behavior

In the above reproduction, I would expect the `u` instance to behave as if it'd been created a la `Test(**obj)`.

### Environment

- ODMantic version: 1.0.2
- MongoDB version: 4.7.2
- Pydantic infos (output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())`):

```
pydantic version: 2.7.2
pydantic-core version: 2.18.3
pydantic-core build: profile=release pgo=true
install path: /workspaces/maven.tse.shepherd/.venv/lib/python3.12/site-packages/pydantic
python version: 3.12.3 (main, May 17 2024, 17:50:29) [GCC 12.2.0]
platform: Linux-5.15.0-107-generic-x86_64-with-glibc2.36
related packages: mypy-1.10.0 fastapi-0.111.0 typing_extensions-4.12.0
commit: unknown
```

- Version of additional modules (if relevant):
- ...

**Additional context**

Server version shouldn't play into this, as it's reproducible standalone, without talking to mongodb at all.

Contributor guide

Open the contributing guide

Research direction

Start by running the standalone Python reproduction from the issue, focusing on Test.model_construct and the later assignment to u.foo. Trace how ODMantic's Model handles constructed instances and attribute changes; done means a model created with model_construct can assign attributes without the reported AttributeError and retains the expected dumped values.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.