BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.94k stars 203 forks source link

[BUG] Exclude Parameter on Model Dump Does Not Work If Lazy Parsing With Embedded Pydantic Models #967

Open ltieman opened 2 weeks ago

ltieman commented 2 weeks ago

Describe the bug A clear and concise description of what the bug is.

.model_dump tries to call the .model_dump method of a pydantic model which is embedded inside a Beanie Document, which is not yet an actual pydantic model, but instead a NotAnObject. As a workaround, we are referencing the parameter which forces the data to be parsed.

Interestingly, we do not see this behavior with the include parameter on .model_dump, and instead it works as expected.

To Reproduce

class SubCollection(BaseModel):
    something: str

class Collection(Document):
    name: str
    sub: SubCollection

item = await Collection.find_one(Collection.id == id, fetch_links=True, lazy_parse=True)
return item.model_dump(exclude={"name":True})

Exception:

pydantic_core._pydantic_core.PydanticSerializationError: Error calling function `<lambda>`: AttributeError: 'NotAnObject' object has no attribute 'model_dump'

This, however, works:

class SubCollection(BaseModel):
    something: str

class Collection(Document):
    name: str
    sub: SubCollection

item = await Collection.find_one(Collection.id == id, fetch_links=True, lazy_parse=True)
item.sub
return item.model_dump(exclude={"name":True})

Expected behavior We are expecting it to return a dictionary with all the keys except for "name"