当前位置: 首页>>代码示例>>Python>>正文


Python mongoengine.EmbeddedDocument方法代码示例

本文整理汇总了Python中mongoengine.EmbeddedDocument方法的典型用法代码示例。如果您正苦于以下问题:Python mongoengine.EmbeddedDocument方法的具体用法?Python mongoengine.EmbeddedDocument怎么用?Python mongoengine.EmbeddedDocument使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mongoengine的用法示例。


在下文中一共展示了mongoengine.EmbeddedDocument方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_ListSpecialField

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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'] 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:22,代码来源:test_fields.py

示例2: test_GenericEmbeddedDocumentField

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 ? 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:25,代码来源:test_fields.py

示例3: test_MapField

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:24,代码来源:test_fields.py

示例4: models

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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() 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:44,代码来源:test_marshmallow_mongoengine.py

示例5: reference_args

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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(), {}) 
开发者ID:graphql-python,项目名称:graphene-mongo,代码行数:22,代码来源:fields.py

示例6: get_relation_kwargs

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:26,代码来源:utils.py

示例7: register

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 
开发者ID:opendatateam,项目名称:udata,代码行数:8,代码来源:extras_fields.py

示例8: validate

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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) 
开发者ID:opendatateam,项目名称:udata,代码行数:28,代码来源:extras_fields.py

示例9: to_python

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
def to_python(self, value):
        if isinstance(value, EmbeddedDocument):
            return value
        return super(ExtrasField, self).to_python(value) 
开发者ID:opendatateam,项目名称:udata,代码行数:6,代码来源:extras_fields.py

示例10: recursive_encoder

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 
开发者ID:yeti-platform,项目名称:yeti,代码行数:28,代码来源:json.py

示例11: is_valid_mongoengine_model

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
def is_valid_mongoengine_model(model):
    return inspect.isclass(model) and (
        issubclass(model, mongoengine.Document)
        or issubclass(model, mongoengine.EmbeddedDocument)
    ) 
开发者ID:graphql-python,项目名称:graphene-mongo,代码行数:7,代码来源:utils.py

示例12: to_representation

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:12,代码来源:fields.py

示例13: represent_data

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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) 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:14,代码来源:fields.py

示例14: get_field_info

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import EmbeddedDocument [as 别名]
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) 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:52,代码来源:utils.py


注:本文中的mongoengine.EmbeddedDocument方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。