odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Allow `exclude_none`, `exclude_unset`, `exclude_defaults` on engine.save()

Open hellocoldworld opened this issue 4 years ago • 0 comments

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:

        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.

hellocoldworld avatar Jul 23 '21 18:07 hellocoldworld