From d42ac7bd1b9e8259c35dd10f92985f46003007e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lelzin=20=CE=BB?= Date: Sun, 27 Oct 2024 16:39:00 -0300 Subject: [PATCH] feat: add `exclude_none` parameter to `model_dump_doc` --- odmantic/model.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/odmantic/model.py b/odmantic/model.py index 08308f29..beb86644 100644 --- a/odmantic/model.py +++ b/odmantic/model.py @@ -709,11 +709,17 @@ def __setattr__(self, name: str, value: Any) -> None: @deprecated( "doc is deprecated, please use model_dump_doc instead", ) - def doc(self, include: Optional["AbstractSetIntStr"] = None) -> Dict[str, Any]: - return self.model_dump_doc(include=include) + def doc( + self, + include: Optional["AbstractSetIntStr"] = None, + exclude_none: bool = False, + ) -> Dict[str, Any]: + return self.model_dump_doc(include=include, exclude_none=exclude_none) def model_dump_doc( - self, include: Optional["AbstractSetIntStr"] = None + self, + include: Optional["AbstractSetIntStr"] = None, + exclude_none: bool = False, ) -> Dict[str, Any]: """Generate a document (BSON) representation of the instance (as a dictionary). @@ -724,7 +730,7 @@ def model_dump_doc( Returns: the document associated to the instance """ - raw_doc = self.model_dump() + raw_doc = self.model_dump(exclude_none=exclude_none) doc = self.__doc(raw_doc, type(self), include) return doc @@ -736,6 +742,8 @@ def __doc( # noqa C901 # TODO: refactor document generation ) -> Dict[str, Any]: doc: Dict[str, Any] = {} for field_name, field in model.__odm_fields__.items(): + if field_name not in raw_doc: + continue if include is not None and field_name not in include: continue if isinstance(field, ODMReference):