art049 / odmantic

Sync and Async ODM (Object Document Mapper) for MongoDB based on python type hints
http://art049.github.io/odmantic
ISC License
1.07k stars 94 forks source link

Unable to validate a document when specifying a reference #498

Open theroucken opened 2 months ago

theroucken commented 2 months ago

In one of the models, I create a reference to another model. When I try to validate the received document using “model_validate_doc”, I get the error “AttributeError: ‘ObjectId’ object has no attribute ‘get’”.

>     Customer.model_validate_doc(customer.model_dump_doc())
>   File ".venv\Lib\site-packages\odmantic\model.py", line 795, in model_validate_doc
>     errors, obj = cls._parse_doc_to_obj(raw_doc)
>                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File ".venv\Lib\site-packages\odmantic\model.py", line 830, in _parse_doc_to_obj
>     sub_errors, sub_obj = field.model._parse_doc_to_obj(
>                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>   File ".venv\Lib\site-packages\odmantic\model.py", line 910, in _parse_doc_to_obj
>     value = raw_doc.get(field.key_name, Undefined)
>             ^^^^^^^^^^^
> AttributeError: 'ObjectId' object has no attribute 'get'
class Shop(Model):
    ...

class Customer(Model):
    user_id: int
    shop: Shop = Reference()

...

shop = await engine.find_one(Shop)
customer = await engine.find_one(Customer, Customer.shop == shop.id)
Customer.model_validate_doc(customer.model_dump_doc())