问题
I want to be able to get a list or some sort of set of fields that are required by the document i've created. For instance, 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 receive:
["nickName","password","joinDate","lastVisited"]
as results for being required fields. Is this possible? If so, how can I achieve the desired result.
Thanks in advance!
回答1:
You can loop through the Class._fields property.
If your class was called User you could 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 so:
>>> 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']
回答2:
This is what I wrote to generate a dict of all the 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
来源:https://stackoverflow.com/questions/8586738/get-required-fields-from-document-in-mongoengine