14

我目前正在探索 MongoEngine“对象文档映射器”的可能性。我目前不清楚的是我可以在多大程度上将我的验证和对象创建逻辑移动到 Document 对象本身。

我的印象是这不应该是一个问题,但我没有找到很多关于问题的示例/警告/最佳实践

  • 在 save() 上自动调用的自定义验证函数以评估字段内容是否有效;
  • 根据字段内容的哈希值在 save() 上自动生成标识符;

我想我需要重写 save() 方法,这样我就可以调用我的自定义逻辑,但是缺乏示例让我相信这可能是一个错误的方法......

欢迎使用任何示例或对使用 mongoEngine 的高质量代码库的引用。

4

3 回答 3

25

现在应该通过在模型上实现该clean()方法来完成自定义验证。

class Essay(Document):
    status = StringField(choices=('Published', 'Draft'), required=True)
    pub_date = DateTimeField()

    def clean(self):
        """
        Ensures that only published essays have a `pub_date` and
        automatically sets the pub_date if published and not set.
        """
        if self.status == 'Draft' and self.pub_date is not None:
            msg = 'Draft entries should not have a publication date.'
            raise ValidationError(msg)

        # Set the pub_date for published items if not set.
        if self.status == 'Published' and self.pub_date is None:
            self.pub_date = datetime.now()

编辑:也就是说,在根据模型定义中设置的规则验证模型之前,您必须小心使用clean()它。validate()

于 2013-09-13T16:15:42.723 回答
15

您可以覆盖save(),但通常需要注意的是您必须调用父类的方法。

如果您发现要为所有模型添加验证钩子,您可以考虑创建一个自定义子类,Document例如:

class MyDocument(mongoengine.Document):

    def save(self, *args, **kwargs):
        for hook in self._pre_save_hooks:
            # the callable can raise an exception if
            # it determines that it is inappropriate
            # to save this instance; or it can modify
            # the instance before it is saved
            hook(self):

        super(MyDocument, self).save(*args, **kwargs)

然后,您可以以相当自然的方式为给定模型类定义挂钩:

class SomeModel(MyDocument):
    # fields...

    _pre_save_hooks = [
        some_callable,
        another_callable
    ]
于 2011-07-06T20:06:59.487 回答
7

您还可以覆盖 Document 上的 validate 方法,但您需要吞下超类 Document 错误,以便将错误添加到它们

不幸的是,这依赖于 MongoEngine 中的内部实现细节,所以谁知道它是否会在未来中断。

class MyDoc(Document):
    def validate(self):
        errors = {}
        try:
            super(MyDoc, self).validate()
        except ValidationError as e:
            errors = e.errors

        # Your custom validation here...
        # Unfortunately this might swallow any other errors on 'myfield'
        if self.something_is_wrong():
            errors['myfield'] = ValidationError("this field is wrong!", field_name='myfield')

        if errors:
            raise ValidationError('ValidationError', errors=errors)

此外,MongoEngine 现在有适当的信号支持来处理其他类型的钩子(例如您在问题中提到的标识符生成)。

http://mongoengine.readthedocs.io/en/latest/guide/signals.html

于 2012-08-22T22:27:37.280 回答