BeanieODM / beanie

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

[BUG] Inheritance: Problems with Settings class #853

Closed DanielBuchberger closed 5 months ago

DanielBuchberger commented 5 months ago

Describe the bug I have taken a shortened version of the inheritance example in the docs. The Bicycle class inherits from Vehicle class. I added Settings class to Bicycle in order to define the name of the MongoDB collection (bicycles). But if I try to insert a Bicycle into the bicycles collection, it ends up in the Vehicle collection. image

To Reproduce

import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from beanie import Document, init_beanie

class Vehicle(Document):
    color: str

    class Settings:
        is_root = True

class Bicycle(Vehicle):

    frame: int
    wheels: int

    class Settings:
        name = 'bicycles'

async def main():
    client = AsyncIOMotorClient(MONGO_CONNECTION_STRING)
    await init_beanie(client.test_db, document_models=[Vehicle, Bicycle])

    bike_1 = await Bicycle(color='black', frame=1, wheels=2).insert()

if __name__ == "__main__":
    asyncio.run(main())

Expected behavior The Bicycle should end up in the bicycles collection, not in the Vehicle collection

Additional context My goal is to create a base class with common properties and let other classes inherit from it. but the child objects shall be stored in different collections. I could not find any example on how to handle the Settings class for inherited classes and achieve the desired behaviour.

DanielBuchberger commented 5 months ago

Ok, I should have tried a few minutes longer. Seems that I have to drop the is_root = True in the base class Vehicle. Then it works.