BeanieODM / beanie

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

[BUG] DeleteRules.DELETE_LINKS is not working? #971

Open dinhtuanan opened 2 months ago

dinhtuanan commented 2 months ago

Describe the bug DeleteRules.DELETE_LINKS is not working. Delete a document success but all linked document didn't

To Reproduce

import asyncio
from typing import Optional

from beanie import BackLink, Document, Link, init_beanie
from beanie.odm.utils.encoder import Encoder
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import Field

from beanie import DeleteRules, WriteRules

class Person(Document):
    name: str
    age: int
    cars: list[Link["Car"]] = Field(default_factory=list)

class Car(Document):
    manufacturer: str
    price: float
    owner: Optional[BackLink[Person]] = Field(default=None, original_field="cars")

async def init():
    client = AsyncIOMotorClient(
        "mongodb://localhost:27017",
    )

    await init_beanie(database=client.test_db, document_models=[Person, Car])

    p1 = Person(
        name="John",
        age=25,
    )    
    p1.cars = [
        Car(manufacturer="Toyota", price=10000),
        Car(manufacturer="BMW", price=20000)
    ]
    await p1.save(link_rule=WriteRules.WRITE)
    # The above code runs fine

    person = await Person.find_one(Person.name == "John")
    print(person)

    # Only person document is deleted, cars didn't
    await person.delete(link_rule=DeleteRules.DELETE_LINKS)

asyncio.run(init())

Expected behavior

Additional context

NuxitBrain commented 1 month ago

Hi ! did you check our car document and if something change inside ? For me ( and maybe i didn't understand) the delete rule just delete the link and not the document. So if you delete the car document, the field cars inside your car document should set to null... Someone can confirm that ?

deivisonmarteleto commented 1 month ago

The import method is not correct. Try it like this:

from beanie.odm.fields import DeleteRules

github-actions[bot] commented 3 days ago

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