Skip to content

Commit

Permalink
Merge pull request #128 from mauro-andre/fix_model_init_remove_list
Browse files Browse the repository at this point in the history
🐛 Fix DbModel init not set None in empty list
  • Loading branch information
mauro-andre authored May 15, 2024
2 parents 7b1f537 + 5b9de31 commit 2b76383
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
4 changes: 2 additions & 2 deletions pyodmongo/models/db_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,11 @@ def __remove_empty_dict(self, dct: dict):
if dct == {}:
return None
for key, value in dct.items():
if value == {} or value == []:
if value == {}:
dct[key] = None
elif type(value) == dict:
dct[key] = self.__remove_empty_dict(dct=value)
is_full_empty = all(v == None or v == {} or v == [] for v in dct.values())
is_full_empty = all(v == None or v == {} for v in dct.values())
if is_full_empty:
return None
return dct
Expand Down
20 changes: 18 additions & 2 deletions tests/test_dict_empty.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class MyModel1(DbModel):

class MyModel2(DbModel):
attr2: str | None
attr2_list: list | None = []
my_model_1: MyModel1 | Id | None
_collection = "my_model_2"

Expand All @@ -16,13 +17,19 @@ class MyModel3(DbModel):
my_model_2: MyModel2 | Id | None
my_model_2_2: MyModel2 | Id | None
my_model_2_3: MyModel2 | Id | None
my_model_2_4: MyModel2 | Id | None
_collection = "my_model_3"

dct = {
"attr3": "attr3",
"my_model_2": {"attr2": "Escrito", "my_model_1": {"attr1": {}}},
"my_model_2_2": {"my_model_1": {}},
"my_model_2": {
"attr2": "Escrito",
"attr2_list": [],
"my_model_1": {"attr1": {}},
},
"my_model_2_2": {"my_model_1": {}, "attr2_list": None},
"my_model_2_3": {},
"my_model_2_4": {"attr2": None, "attr2_list": [], "my_model_1": {}},
}
obj = MyModel3(**dct)
assert obj.model_dump() == {
Expand All @@ -32,10 +39,19 @@ class MyModel3(DbModel):
"created_at": None,
"updated_at": None,
"attr2": "Escrito",
"attr2_list": [],
"my_model_1": None,
},
"my_model_2_2": None,
"my_model_2_3": None,
"my_model_2_4": {
"id": None,
"created_at": None,
"updated_at": None,
"attr2": None,
"attr2_list": [],
"my_model_1": None,
},
"id": None,
"created_at": None,
"updated_at": None,
Expand Down

0 comments on commit 2b76383

Please sign in to comment.