Allow `exclude_none`, `exclude_unset`, `exclude_defaults` on engine.save()
- Dominant language
- Python
- Stars
- 1.2k
- Forks
- 97
- PR merge metrics
- No merged PRs in 30d
Description
# Feature request
### Context
I need to save ODMantic documents, but almost always I need to save them in a way that unset fields are not persisted in mongoDB. This is mainly because unsetted fields should not be included in unique, sparse indexes. Also I can see how exclude_none and exclude_defaults can be useful.
### Solution
I think that `engine.save` should allow `exclude_none`, `exclude_unset` and `exclude_defaults` as keyword arguments in its. public API, just like `Pydantic.BaseModel.dict`. I would expect that when passing any of this excluding argument, the fields that are none/unset/default value would not be persisted in the DB.
#### Alternative solutions
Currently I am working with this approach:
```python
doc = request.dict(exclude_unset=True)
id_ = await engine.get_collection(self.model).insert_one(doc)
result = await engine.find_one(self.model, self.model.id == id_.inserted_id)
```
but I think it's ugly and should be probably handled better in ODMantic right away.
What do you think of this idea? I could perhaps help with a PR with some guidance.
Contributor guide
Research direction
Start at the engine.save API and follow how ODMantic serializes documents before writing them to MongoDB. Compare the requested exclude_none, exclude_unset, and exclude_defaults behavior with Pydantic.BaseModel.dict; done means each option is accepted and excluded fields are absent from persisted documents.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb, python
- Domain
- databases
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100