Python mongoengine.EmbeddedDocument() Examples

The following are 14 code examples of mongoengine.EmbeddedDocument(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mongoengine , or try the search function .
Example #1
Source File: test_fields.py    From marshmallow-mongoengine with MIT License 7 votes vote down vote up
def test_MapField(self):
        class MappedDoc(me.EmbeddedDocument):
            field = me.StringField()
        class Doc(me.Document):
            id = me.IntField(primary_key=True, default=1)
            map = me.MapField(me.EmbeddedDocumentField(MappedDoc))
            str = me.MapField(me.StringField())
        fields_ = fields_for_model(Doc)
        assert type(fields_['map']) is fields.Map
        class DocSchema(ModelSchema):
            class Meta:
                model = Doc
        doc = Doc(map={'a': MappedDoc(field='A'), 'b': MappedDoc(field='B')},
                  str={'a': 'aaa', 'b': 'bbbb'}).save()
        dump = DocSchema().dump(doc)
        assert not dump.errors
        assert dump.data == {'map': {'a': {'field': 'A'}, 'b': {'field': 'B'}},
                             'str': {'a': 'aaa', 'b': 'bbbb'}, 'id': 1}
        # Try the load
        load = DocSchema().load(dump.data)
        assert not load.errors
        assert load.data.map == doc.map 
Example #2
Source File: test_fields.py    From marshmallow-mongoengine with MIT License 6 votes vote down vote up
def test_ListSpecialField(self):
        class NestedDoc(me.EmbeddedDocument):
            field = me.StringField()
        class Doc(me.Document):
            list = me.ListField(me.EmbeddedDocumentField(NestedDoc))
        fields_ = fields_for_model(Doc)
        assert type(fields_['list']) is fields.List
        assert type(fields_['list'].container) is fields.Nested
        class DocSchema(ModelSchema):
            class Meta:
                model = Doc
        list_ = [{'field': 'A'}, {'field': 'B'}, {'field': 'C'}]
        doc = Doc(list=list_)
        dump = DocSchema().dump(doc)
        assert not dump.errors
        assert dump.data == {'list': list_}
        load = DocSchema().load(dump.data)
        assert not load.errors
        for i, elem in enumerate(list_):
            assert load.data.list[i].field == elem['field'] 
Example #3
Source File: test_fields.py    From marshmallow-mongoengine with MIT License 6 votes vote down vote up
def test_GenericEmbeddedDocumentField(self):
        class Doc(me.Document):
            id = me.StringField(primary_key=True, default='main')
            embedded = me.GenericEmbeddedDocumentField()
        class EmbeddedA(me.EmbeddedDocument):
            field_a = me.StringField(default='field_a_value')
        class EmbeddedB(me.EmbeddedDocument):
            field_b = me.IntField(default=42)
        fields_ = fields_for_model(Doc)
        assert type(fields_['embedded']) is fields.GenericEmbeddedDocument
        class DocSchema(ModelSchema):
            class Meta:
                model = Doc
        doc = Doc(embedded=EmbeddedA())
        dump = DocSchema().dump(doc)
        assert not dump.errors
        assert dump.data == {'embedded': {'field_a': 'field_a_value'}, 'id': 'main'}
        doc.embedded = EmbeddedB()
        doc.save()
        dump = DocSchema().dump(doc)
        assert not dump.errors
        assert dump.data == {'embedded': {'field_b': 42}, 'id': 'main'}
        # TODO: test load ? 
Example #4
Source File: test_marshmallow_mongoengine.py    From marshmallow-mongoengine with MIT License 6 votes vote down vote up
def models():

    class HeadTeacher(me.EmbeddedDocument):
        full_name = me.StringField(max_length=255, unique=True, default='noname')

    class Course(me.Document):
        id = me.IntField(primary_key=True)
        name = me.StringField()
        # These are for better model form testing
        cost = me.IntField()
        description = me.StringField()
        level = me.StringField(choices=('Primary', 'Secondary'))
        prereqs = me.DictField()
        started = me.DateTimeField()
        grade = AnotherIntegerField()
        students = me.ListField(me.ReferenceField('Student'))

    class School(me.Document):
        name = me.StringField()
        students = me.ListField(me.ReferenceField('Student'))
        headteacher = me.EmbeddedDocumentField(HeadTeacher)

    class Student(me.Document):
        full_name = me.StringField(max_length=255, unique=True, default='noname')
        age = me.IntField(min_value=10, max_value=99)
        dob = me.DateTimeField(null=True)
        date_created = me.DateTimeField(default=dt.datetime.utcnow,
                                        help_text='date the student was created')
        current_school = me.ReferenceField('School')
        courses = me.ListField(me.ReferenceField('Course'))
        email = me.EmailField(max_length=100)
        profile_uri = me.URLField(max_length=200)

    # So that we can access models with dot-notation, e.g. models.Course
    class _models(object):

        def __init__(self):
            self.HeadTeacher = HeadTeacher
            self.Course = Course
            self.School = School
            self.Student = Student
    return _models() 
Example #5
Source File: utils.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def get_relation_kwargs(field_name, relation_info):
    """
    Creating a default instance of a flat relational field.
    """
    model_field, related_model = relation_info
    kwargs = {}
    if related_model and not issubclass(related_model, EmbeddedDocument):
        kwargs['queryset'] = related_model.objects

    if model_field:
        if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
            kwargs['label'] = capfirst(model_field.verbose_name)
        if hasattr(model_field, 'help_text'):
            kwargs['help_text'] = model_field.help_text

        kwargs['required'] = model_field.required

        if model_field.null:
            kwargs['allow_null'] = True
        if getattr(model_field, 'unique', False):
            validator = UniqueValidator(queryset=related_model.objects)
            kwargs['validators'] = [validator]

    return kwargs 
Example #6
Source File: extras_fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def register(self, key, dbtype):
        '''Register a DB type to add constraint on a given extra key'''
        if not issubclass(dbtype, (BaseField, EmbeddedDocument)):
            msg = 'ExtrasField can only register MongoEngine fields'
            raise TypeError(msg)
        self.registered[key] = dbtype 
Example #7
Source File: extras_fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, value):
        super(ExtrasField, self).validate(value)

        errors = {}
        for key, value in value.items():
            extra_cls = self.registered.get(key)

            if not extra_cls:
                if not isinstance(value, ALLOWED_TYPES):
                    types = ', '.join(t.__name__ for t in ALLOWED_TYPES)
                    msg = 'Value should be an instance of: {types}'
                    errors[key] = msg.format(types=types)
                continue

            try:
                if issubclass(extra_cls, EmbeddedDocument):
                    (value.validate()
                     if isinstance(value, extra_cls)
                     else extra_cls(**value).validate())
                else:
                    extra_cls().validate(value)
            except Exception as e:
                errors[key] = getattr(e, 'message', str(e))

        if errors:
            self.error('Unsupported types', errors=errors) 
Example #8
Source File: extras_fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, EmbeddedDocument):
            return value
        return super(ExtrasField, self).to_python(value) 
Example #9
Source File: json.py    From yeti with Apache License 2.0 5 votes vote down vote up
def recursive_encoder(objects, template=None, ctx=None):
    if isinstance(objects, dict):
        newdict = {}
        for (key, value) in objects.items():
            newdict[key] = recursive_encoder(value)
        return newdict

    elif isinstance(objects, (list, QuerySet, set)):
        return [recursive_encoder(o) for o in objects]

    elif isinstance(objects, tuple):
        return tuple(recursive_encoder(o) for o in objects)

    elif isinstance(objects, (ObjectId, DBRef, datetime.datetime)):
        return to_json(objects)

    elif isinstance(objects,
                    (Node, Link, YetiDocument, Document, EmbeddedDocument)):
        if hasattr(objects, "info"):
            data = objects.info()
        else:
            data = objects.to_mongo()
        return recursive_encoder(data)

    else:
        return objects 
Example #10
Source File: fields.py    From graphene-mongo with MIT License 5 votes vote down vote up
def reference_args(self):
        def get_reference_field(r, kv):
            field = kv[1]
            mongo_field = getattr(self.model, kv[0], None)
            if isinstance(
                mongo_field,
                (mongoengine.LazyReferenceField, mongoengine.ReferenceField),
            ):
                field = convert_mongoengine_field(mongo_field, self.registry)
            if callable(getattr(field, "get_type", None)):
                _type = field.get_type()
                if _type:
                    node = _type._type._meta
                    if "id" in node.fields and not issubclass(
                        node.model, (mongoengine.EmbeddedDocument,)
                    ):
                        r.update({kv[0]: node.fields["id"]._type.of_type()})
            return r

        return reduce(get_reference_field, self.fields.items(), {}) 
Example #11
Source File: utils.py    From graphene-mongo with MIT License 5 votes vote down vote up
def is_valid_mongoengine_model(model):
    return inspect.isclass(model) and (
        issubclass(model, mongoengine.Document)
        or issubclass(model, mongoengine.EmbeddedDocument)
    ) 
Example #12
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def to_representation(self, doc):
        if not isinstance(doc, EmbeddedDocument):
            self.fail('not_a_doc', input_type=type(doc).__name__)
        data = OrderedDict()
        data['_cls'] = doc.__class__.__name__
        for field_name in doc._fields:
            if not hasattr(doc, field_name):
                continue
            data[field_name] = getattr(doc, field_name)
        return data 
Example #13
Source File: fields.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def represent_data(self, data):
        if isinstance(data, EmbeddedDocument):
            field = GenericEmbeddedField()
            return field.to_representation(data)
        elif isinstance(data, dict):
            return dict([(key, self.represent_data(val)) for key, val in data.items()])
        elif isinstance(data, list):
            return [self.represent_data(value) for value in data]
        elif data is None:
            return None
        else:
            return smart_str(data, strings_only=True) 
Example #14
Source File: utils.py    From django-rest-framework-mongoengine with MIT License 4 votes vote down vote up
def get_field_info(model):
    """
    Given a model class, returns a `FieldInfo` instance, which is a
    `namedtuple`, containing metadata about the various field types on the model
    including information about their relationships.
    """
    # Deal with the primary key.
    if issubclass(model, mongoengine.EmbeddedDocument):
        pk = None
    else:
        pk = model._fields[model._meta['id_field']]

    # Deal with regular fields.
    fields = OrderedDict()

    # Deal with forward relationships.
    # Pass forward relations since there is no relations on mongodb
    references = OrderedDict()

    embedded = OrderedDict()

    def add_field(name, field):
        if isinstance(field, REFERENCING_FIELD_TYPES):
            references[name] = get_relation_info(field)
        elif isinstance(field, EMBEDDING_FIELD_TYPES):
            embedded[name] = get_relation_info(field)
        elif isinstance(field, COMPOUND_FIELD_TYPES):
            fields[name] = field
            if field.field:
                add_field(name + '.child', field.field)
        elif field is pk:
            return
        else:
            fields[name] = field

    for field_name in model._fields_ordered:
        add_field(field_name, model._fields[field_name])

    # Shortcut that merges both regular fields and the pk,
    # for simplifying regular field lookup.
    fields_and_pk = OrderedDict()
    fields_and_pk['pk'] = pk
    fields_and_pk[getattr(pk, 'name', 'pk')] = pk
    fields_and_pk.update(fields)

    return FieldInfo(pk,
                     fields,
                     references,
                     fields_and_pk,
                     embedded)