Get required fields from a document in mongoengine?

I want to be able to get a list or some set of fields that are required for the document that I created. For example, here is my 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() 

^ From this document I should get:

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

as results for required fields. Is it possible? If so, how can I achieve the desired result.

Thanks in advance!

+7
source share
2 answers

You can skip the Class._fields property.

If your class was called by User, you can do this:

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

To get a sorted list based on creation, you can use the creation counter like this:

 >>> 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'] 
+12
source

This is what I wrote to create a dict of all fields and their nested types.

 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 
+1
source

All Articles