简体   繁体   中英

How do I cascade delete in this scenario using MongoEngine?

I have this simple model:

from mongoengine import *
from datetime import datetime

class Person(Document):
    firstname = StringField(required=True)

    @property
    def comments(self):
        return Comment.objects(author=self).all()

class Comment(Document):
    text = StringField(required=True)
    timestamp = DateTimeField(required=True, default=datetime.now())
    author = ReferenceField('Person', required=True, reverse_delete_rule=CASCADE)

class Program(Document):
    title = StringField(required=True)
    comments = ListField(ReferenceField('Comment'))

class Episode(Document):
    title = StringField(required=True)
    comments = ListField(ReferenceField('Comment'))

As you can see, both Programs and Episodes can have comments. Initially, I tried to embed the comments but I seemed to run into a brick wall. So I'm trying Comments as a Document class instead. My question is, how do I model it so that:

  1. When a Person is deleted, so are all their comments
  2. When a Comment is deleted (either directly or indirectly), it is removed from its parent
  3. When a Program or Episode is deleted, so are the Comment objects

I'm use to doing all this manually in MongoDB (and SQLa, for that matter), but I'm new to MongoEngine and I'm struggling a bit. Any help would be awesome!

Not all of these are possible without writing application code to handle the logic. I would write signals to handle some of the edge cases.

The main issue you have is global updates / removes aren't handled - so you'd have to ensure that the api you write in the api is used, to ensure a clean database state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM