验证必填字段-MongoEngine

时间:2019-06-29 21:39:10

标签: python-3.x mongodb mongoengine

我为RSS feed创建了一个类:

from mongoengine import *

class RSS(Document):
    time_added = DateTimeField(default=datetime.datetime.utcnow)

    link = StringField(required=True)
    title = StringField(required=True)
    last_entry_id = StringField(required=True)
    last_etag = StringField()
    last_modified = DateTimeField()

    subscribed = ListField(IntField(), required=True)

    meta = {
        'collection': 'rss',
        'indexes': ['$title']
    }

根据我的要求,我希望这样做,以便在last_etaglast_modified字段中出现 两者需要)。在MongoEngine中有可能吗?

1 个答案:

答案 0 :(得分:1)

对于多字段验证,您可以覆盖Document.clean方法,例如

from mongoengine import *
import datetime as dt

class RSS(Document):
    etag = StringField()
    last_modified = DateTimeField()

    def clean(self):
        if not self.etag and not self.last_modified:
            raise ValidationError('etag and or last_modified are required')


RSS().save()    # Fails with ValidationError (etag and/or last_modified are required)
RSS(etag='123456789').save()                                        # passes
RSS(etag='123456789', last_modified=dt.datetime.utcnow()).save()    # passes

您可以查看docs以获得更多信息。