2011-12-21 52 views
7

我希望能夠獲得我創建的文檔所需的列表或某種字段集合。舉例來說,這裏是我的文檔:從mongoengine的Document中獲取必填字段?

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"] 

的結果是必填項。這可能嗎?如果是這樣,我怎麼能達到預期的結果。

在此先感謝!

回答

12

您可以遍歷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'] 
+0

關於錢,謝謝一堆! – AlfredN 2011-12-21 09:11:08

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 
+0

我覆蓋了我正在使用的字段,如果此代碼無法迭代,則可能必須添加更多條件。 – harry 2015-07-19 10:52:54