BeanieODM / beanie

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

[BUG] updating/setting a nested parameter inside another does not understand `alias` and stores "new" attribute. #369

Closed IGJAmpere closed 1 year ago

IGJAmpere commented 1 year ago

Bug description

Basically, the only moment where the alias seems to be properly managed is for the Document. The attributes of nested pydantic models cannot be declared through the attribute name.

It is also important to consider that linters will be unable to understand the alias, but they do understand the attribute.

Bug reproduction

import asyncio
from typing import Optional
from beanie import Document, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import Field, BaseModel, BaseConfig

class B(BaseModel):
    b_thing: int = Field(alias="bThing")

    class Config(BaseConfig):
        allow_population_by_field_name: bool = True

class A(Document):
    a_thing: int = Field(alias="aThing")
    thing: Optional[B]

    class Settings:
        name = "as"

async def main():

    client = AsyncIOMotorClient("mongodb://localhost:27017")

    db_name = client.db_name  # type: ignore
    await init_beanie(database=db_name, document_models=[A])

    await A.find_all().delete()

    await A(a_thing=3, thing=B(b_thing=3)).insert()

    # should understand that `b_thing` is to be transformed into  `bThing` in the DB.
    await A.find_one().set({A.thing.b_thing: 4})

if __name__ == "__main__":

    asyncio.run(main())

Expected behaviour

As the alias is respected for the main Document, it is expected that the same happens for nested objects. But this does not happen.

Hopefully this can get fixed. Thank you!

github-actions[bot] commented 1 year ago

This issue is stale because it has been open 30 days with no activity.

github-actions[bot] commented 1 year ago

This issue was closed because it has been stalled for 14 days with no activity.