Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix optional embedded model definition #273

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion odmantic/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,9 @@ def __doc(
elif isinstance(field, ODMEmbedded):
doc[field.key_name] = self.__doc(raw_doc[field_name], field.model, None)
elif isinstance(field, ODMEmbeddedGeneric):
if field.generic_origin is dict:
if raw_doc[field_name] is None:
doc[field.key_name] = None
elif field.generic_origin is dict:
doc[field.key_name] = {
item_key: self.__doc(item_value, field.model)
for item_key, item_value in raw_doc[field_name].items()
Expand Down Expand Up @@ -846,6 +848,8 @@ def _parse_doc_to_obj( # noqa C901 # TODO: refactor document parsing
else:
value[item_key] = item_value
obj[field_name] = value
elif raw_value is None:
value = None
else:
errors.append(
ErrorWrapper(
Expand Down
34 changes: 33 additions & 1 deletion tests/integration/test_embedded_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, List, Tuple
from typing import Dict, List, Tuple, Union

import pytest

Expand Down Expand Up @@ -311,3 +311,35 @@ class Out(Model):
sync_engine.save(instance)
fetched = sync_engine.find_one(Out)
assert instance == fetched


async def test_embedded_model_with_missing_default(
aio_engine: AIOEngine,
):
class E(EmbeddedModel):
f: int

class M(Model):
e: Union[E, None]

m = M()
assert m.e is None
await aio_engine.save(m)
fetched = await aio_engine.find_one(M)
assert fetched is not None and fetched.e is None


def test_sync_embedded_model_with_missing_default(
sync_engine: SyncEngine,
):
class E(EmbeddedModel):
f: int

class M(Model):
e: Union[E, None]

m = M()
assert m.e is None
sync_engine.save(m)
fetched = sync_engine.find_one(M)
assert fetched is not None and fetched.e is None