Here is some field in a Document using mongoengine

_id     = f.ObjectIdField(db_field="i", required=True)
name    = f.StringField(db_field="n")

I would like to loop through each field in the Document and see if they are type XField and is_required is True, is there a way of doing that?

I know you can list out all fields using _fields

but

for field in SomeDocument._fields:
    print type(field) # always return 'str' not 'StringField' or 'ObjectField'

    # Don't know how to check is_required

Any help would be appreciated.

2

There are 2 answers

0
jimjkelly On

The issue you were having is that SomeDocument._fields is a dictionary, so iterating on it is giving you the keys (which are strings). For instance if you have a field foo, you can do SomeDocument._fields['foo'].required. And of course you can do something like:

for field in SomeDocument._fields:
    print '{} {} required.'.format(SomeDocument._fields[field], 'is' if SomeDocument._fields[field].required else 'is not')
0
Rajesh Kaushik On

You can simply use this

field_dict = SomeDocument.get_fields_info()
for field_name, field in field_dict.iteritems():
    print field_name, field.required, field.__class__