从mongoengine的Document获取必填字段?

时间:2011-12-21 08:13:02

标签: python mongodb mongoengine

我希望能够获得我创建的文档所需的列表或某种字段集。例如,这是我的文件:

nickName        = StringField(required=True)
password        = StringField(required=True)
firstName       = StringField()
lastName        = StringField()
joinDate        = DateTimeField(required=True)
lastVisited     = DateTimeField(required=True)
subscriptions   = DictField(field=ObjectIdField())
isActivated     = BooleanField(default=True)
profileImage    = FileField()
isModerator     = BooleanField(default=False)
description     = StringField()
location        = GeoPointField()
email           = EmailField()
settings        = DictField()

^从这份文件我应该收到:

["nickName","password","joinDate","lastVisited"]

作为必填字段的结果。这可能吗?如果是这样,我怎样才能达到预期的效果。

提前致谢!

2 个答案:

答案 0 :(得分:16)

您可以遍历Class._fields属性。

如果您的班级名为“用户”,则可以执行以下操作:

>>> [k for k,v in User._fields.iteritems() if v.required]
['joinDate', 'password', 'nickName', 'lastVisited']

要根据创建获得排序列表,您可以使用创建计数器,如下所示:

>>> from operator import itemgetter
>>> required_fields = ((v.creation_counter, k) for k,v in User._fields.iteritems() if v.required)
>>> sorted_required_fields = map(itemgetter(1), sorted(required_fields, key=itemgetter(0)))
>>> sorted_required_fields
['nickName', 'password', 'joinDate', 'lastVisited']

答案 1 :(得分:1)

这是我写的所有字段及其嵌套类型的字典。

from mongoengine.fields import (
    IntField,
    BooleanField,
    StringField,
    DateTimeField,
    DecimalField,
    FloatField,
    LongField,
    ListField,
    EmbeddedDocumentField,
    ReferenceField,
)

__input_types = {
    IntField,
    BooleanField,
    StringField,
    DateTimeField,
    DecimalField,
    FloatField,
    LongField,
}

__input_num_types = {
    IntField,
    BooleanField,
    DecimalField,
    FloatField,
    LongField,
}

def list_schema(m):
    """list all the field in the model
    and in the nested models"""
    sdict = {}
    for k, v in m._fields.iteritems():
        if k == '_cls':
            continue

        ftype = type(v)
        if ftype in __input_types:
            sdict[k] = {
                'default': v.default if v.default else '',
                'is_num': ftype in __input_num_types,
                'required': v.required,
            }
        elif ftype == ListField:
            seqtype = v.field
            if seqtype in __input_types:
                sdict[k] = [{
                    'default': v.default() if v.default else '',
                    'is_num': seqtype in __input_num_types,
                    'required': v.required,
                }]
            else:
                sdict[k] = [list_schema(seqtype.document_type)]
        else:
            sdict[k] = list_schema(v.document_type)
    return sdict