Python 普遍更新为 child class

Python generalized update to child class

如果我class喜欢:

class UpdateDocument(Document):
    modified_date = DateTimeField()
    meta = {'allow_inheritance': True}

    def save(self, *args, **kwargs):
        self.modified_date = datetime.utcnow()
        return super(UpdateDocument, self).save(*args, **kwargs)

这行不通,因为如果它被另一个文档继承,它将无法将自己保存到自己的 class,例如:

 class New(UpdateDocument):
      name = StringField()

当您保存它时,它将作为 UpdateDocument 插入到数据库中。概括保存方法的解决方法是什么。这也是更新索引问题的一部分,但我更关心的是平衡 class 继承。

一种解决方案是使用 mongoengine 中的 signals 功能。来自文档:

from datetime import datetime

from mongoengine import *
from mongoengine import signals

def update_modified(sender, document):
    document.modified = datetime.utcnow()

class Record(Document):
    modified = DateTimeField()

signals.pre_save.connect(update_modified)

这将在保存之前将 update_modified 方法应用于所有文档。您还可以根据文档使用 class 方法:

class Author(Document):
    name = StringField()

    @classmethod
    def pre_save(cls, sender, document, **kwargs):
        logging.debug("Pre Save: %s" % document.name)

    @classmethod
    def post_save(cls, sender, document, **kwargs):
        logging.debug("Post Save: %s" % document.name)
        if 'created' in kwargs:
            if kwargs['created']:
                logging.debug("Created")
            else:
                logging.debug("Updated")

signals.pre_save.connect(Author.pre_save, sender=Author)
signals.post_save.connect(Author.post_save, sender=Author)