Skip to content

Commit

Permalink
Handle missing references while parsing a document
Browse files Browse the repository at this point in the history
  • Loading branch information
art049 committed Oct 27, 2020
1 parent 909a9e3 commit 6f3ebc2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 4 additions & 1 deletion odmantic/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,10 @@ def parse_doc(cls: Type[TBase], raw_doc: Dict) -> TBase:
doc: Dict[str, Any] = {}
for field_name, field in cls.__odm_fields__.items():
if isinstance(field, ODMReference):
doc[field_name] = field.model.parse_doc(raw_doc[field.key_name])
sub_doc = raw_doc.get(field.key_name)
if sub_doc is None:
continue # The error will be handled while parsing the object
doc[field_name] = field.model.parse_doc(sub_doc)
else:
field = cast(Union[ODMField, ODMEmbedded], field)
value = raw_doc.get(field.key_name, field.get_default_importing_value())
Expand Down
14 changes: 14 additions & 0 deletions tests/integration/test_engine_reference.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pytest

from odmantic.bson import ObjectId
from odmantic.engine import AIOEngine
from odmantic.exceptions import DocumentParsingError
from odmantic.model import Model
from odmantic.reference import Reference
from tests.zoo.deeply_nested import NestedLevel1, NestedLevel2, NestedLevel3
Expand Down Expand Up @@ -80,3 +82,15 @@ class M(Model):
fetched = await engine.find_one(M)
assert fetched is not None
assert fetched.r.field == 3


async def test_reference_not_set_in_database(engine: AIOEngine):
class R(Model):
field: int

class M(Model):
r: R = Reference()

await engine.get_collection(M).insert_one({"_id": ObjectId()})
with pytest.raises(DocumentParsingError, match="r required"):
await engine.find_one(M)

0 comments on commit 6f3ebc2

Please sign in to comment.