How to use the mongoengine.EmbeddedDocument function in mongoengine

To help you get started, we’ve selected a few mongoengine examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MongoEngine / mongoengine / tests / fields / fields.py View on Github external
def test_dynamic_fields_embedded_class(self):
        class Embed(EmbeddedDocument):
            field_1 = StringField(db_field="f")

        class Doc(Document):
            my_id = IntField(primary_key=True)
            embed_me = DynamicField(db_field="e")
            field_x = StringField(db_field="x")

        Doc.drop_collection()

        Doc(my_id=1, embed_me=Embed(field_1="hello"), field_x="x").save()

        doc = Doc.objects.get()
        self.assertEqual(doc.embed_me.field_1, "hello")
github gitaarik / monkful / tests / apps / basic_resource / documents.py View on Github external
from datetime import datetime
from bson import ObjectId
from mongoengine import Document, EmbeddedDocument, fields


class Vote(EmbeddedDocument):
    ip_address = fields.StringField(unique=True)
    name = fields.StringField()
    date = fields.DateTimeField(default=datetime.now)


class Comment(EmbeddedDocument):
    id = fields.ObjectIdField(unique=True, default=ObjectId)
    text = fields.StringField()
    date = fields.DateTimeField(default=datetime.now)
    email = fields.EmailField()
    upvotes = fields.ListField(fields.EmbeddedDocumentField(Vote))


class Article(Document):
    title = fields.StringField(unique=True)
    text = fields.StringField()
    comments = fields.ListField(fields.EmbeddedDocumentField(Comment))
    top_comment = fields.EmbeddedDocumentField(Comment)
    tags = fields.ListField(fields.StringField())
    publish = fields.BooleanField()
    publish_date = fields.DateTimeField()
    version = fields.FloatField()
github hiroaki-yamamoto / mongoengine-goodjson / tests / integration / fixtures / reference.py View on Github external
#!/usr/bin/env python
# coding=utf-8

"""Fixtures for integration tests."""

from bson import ObjectId

import mongoengine as db
import mongoengine_goodjson as gj

from .articles import Article
from .base import Dictable
from .user import User


class ExtraInformation(Dictable, db.EmbeddedDocument):
    """Extra information."""

    txt = db.StringField()

    @classmethod
    def generate_test_data(cls, additional_suffix=""):
        """Generate test data."""
        return cls(
            txt=("This is a test{}").format(
                (" {}").format(additional_suffix) if additional_suffix else
                ""
            )
        )


class ExtraReference(Dictable, db.Document):
github marrow / contentment / web / extras / contentment / components / asset / model.py View on Github external
'AllUsersACLRule',
        'AnonymousUsersACLRule',
        'AuthenticatedUsersACLRule',
        'OwnerACLRule',
        'UserACLRule',
        'GroupACLRule',
        'AdvancedACLRule'
    ]



particles = u"""able abst added almost alone along already also although always among amongst and announce another any anybody anyhow anymore anyone anything anyway anyways anywhere apparently approximately are aren arent aren't arise around aside ask asking auth available away awfully back became because become becomes becoming been before beforehand begin beginning beginnings begins behind being believe below beside besides between beyond biol both brief briefly but came can cannot can't cause causes certain certainly come comes contain containing contains could couldnt date did didn't different does doesn't doing done don't down downwards due during each edu effect eight eighty either else elsewhere end ending enough especially et-al etc even ever every everybody everyone everything everywhere except far few fifth first five fix followed following follows for former formerly forth found four from further furthermore gave get gets getting give given gives giving goes gone got gotten had happens hardly has hasn't have haven't having hed hence her here hereafter hereby herein heres hereupon hers herself hes hid him himself his hither home how howbeit however hundred i'll i'm immediate immediately importance important indeed index information instead into invention inward isn't itd it'd it'll its itself i've just jk keep keeps kept keys know known knows largely last lately later latter latterly least less lest let lets like liked likely line little 'll look looking looks ltd made mainly make makes many may maybe mean means meantime meanwhile merely might million miss more moreover most mostly mrs much mug must myself name namely nay near nearly necessarily necessary need needs neither never nevertheless new next nine ninety nobody non none nonetheless noone nor normally nos not noted nothing now nowhere obtain obtained obviously off often okay old omitted once one ones only onto ord other others otherwise ought our ours ourselves out outside over overall owing own page pages part particular particularly past per perhaps placed please plus poorly possible possibly potentially predominantly present previously primarily probably promptly proud provides put que quickly quite ran rather readily really recent recently ref refs regarding regardless regards related relatively research respectively resulted resulting results right run said same saw say saying says sec section see seeing seem seemed seeming seems seen self selves sent seven several shall she shed she'll shes should shouldn't show showed shown showns shows significant significantly similar similarly since six slightly some somebody somehow someone somethan something sometime sometimes somewhat somewhere soon sorry specifically specified specify specifying still stop strongly sub substantially successfully such sufficiently suggest sup sure take taken taking tell tends than thank thanks thanx that that'll thats that've the their theirs them themselves then thence there thereafter thereby thered therefore therein there'll thereof therere theres thereto thereupon there've these they theyd they'll theyre they've think this those thou though thoughh thousand throug through throughout thru thus til tip to together too took toward towards tried tries truly try trying twice two under unfortunately unless unlike unlikely until unto up upon ups us use used useful usefully usefulness uses using usually value various 've very via viz vol vols want wants was wasn't way wed welcome we'll went were weren't we've what whatever what'll whats when whence whenever where whereafter whereas whereby wherein wheres whereupon wherever whether which while whim whither who whod whoever whole who'll whom whomever whos whose why widely willing wish with within without won't words world would wouldn't www yes yet you youd you'll your youre yours yourself yourselves you've zero what're""".split()
particles = []


class ACLRule(db.EmbeddedDocument):
    def __str__(self):
        return self.__class__.__name__

class InheritACLRules(ACLRule):
    pass

class BaseACLRule(ACLRule):
    def __str__(self):
        return self.__class__.__name__ + "(" + ("allow" if self.allow else "deny") + ", " + self.permission + ")"
    
    allow = db.BooleanField()
    permission = db.StringField(max_length=250)
    inheritable = db.BooleanField(default=True)
    
    def __call__(self, entity, identity, kind, name):
        kind_, _, name_ = self.permission.partition(':')
github UWFlow / rmc / models / review.py View on Github external
return {
            'me': Privacy.ME,
            'friends': Privacy.FRIENDS,
            'everyone': Privacy.EVERYONE,
        }.get(str_privacy, default)

    @staticmethod
    def to_str(int_privacy, default='friends'):
        return {
            Privacy.ME: 'me',
            Privacy.FRIENDS: 'friends',
            Privacy.EVERYONE: 'everyone',
        }.get(int_privacy, default)


class BaseReview(me.EmbeddedDocument):
    comment = me.StringField(default='', max_length=4096)
    comment_date = me.DateTimeField()
    share_date = me.DateTimeField()
    # The time that any rating for this review was changed
    # (either created, modified, or deleted)
    rating_change_date = me.DateTimeField()
    privacy = me.IntField(choices=Privacy.choices(), default=Privacy.FRIENDS)

    # Minimum number of characters for a review to pass
    # TODO(david): Have a function to do this. First, we need consistent review
    #     interface
    MIN_REVIEW_LENGTH = 11

    def __init__(self, **kwargs):
        if 'ratings' in kwargs:
            kwargs.update({d['name']: d['rating'] for d in kwargs['ratings']})
github josiah-wolf-oberholtzer / discograph / discograph / library / mongo / ArtistReference.py View on Github external
# -*- encoding: utf-8 -*-
import mongoengine
from discograph.library.mongo.MongoModel import MongoModel


class ArtistReference(MongoModel, mongoengine.EmbeddedDocument):

    ### MONGOENGINE FIELDS ###

    discogs_id = mongoengine.IntField()
    name = mongoengine.StringField()

    ### PUBLIC METHODS ###

    @classmethod
    def from_members(cls, members):
        result = []
        if members is None or not len(members):
            return result
        for i in range(0, len(members), 2):
            discogs_id = int(members[i].text)
            name = members[i + 1].text
github IRC-SPHERE / HyperStream / models / time_interval.py View on Github external
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
#  OR OTHER DEALINGS IN THE SOFTWARE.

from mongoengine import EmbeddedDocument, DateTimeField


class TimeIntervalModel(EmbeddedDocument):
    start = DateTimeField(required=True)
    end = DateTimeField(required=True)
github nditech / apollo / apollo / core / documents.py View on Github external
# Locations
class Sample(Document):
    '''Samples allow for the storage of groups of Locations that can be used
    to create samples for analysis or data management.'''

    name = StringField()
    events = ListField(ReferenceField('Event'))

    meta = {
        'indexes': [
            ['events']
        ]
    }


class LocationTypeAncestor(EmbeddedDocument):
    '''An embedded document used by the :class:`core.document.LocationType`
    model for storing denormalized ancestry data'''

    name = StringField()


class LocationType(Document):
    '''Stores the type describing the administrative level of a Location
    :attr ancestors_ref: This stores a list references to ancestor
    loction types as documented in
    http://docs.mongodb.org/manual/tutorial/model-tree-structures/'''

    name = StringField()
    ancestors_ref = ListField(ReferenceField('LocationType'))
    on_submissions_view = BooleanField(default=False)
    on_dashboard_view = BooleanField(default=False)
github qinxuye / cola / app / weibo / storage.py View on Github external
]
    }
    
class EduInfo(EmbeddedDocument):
    name = StringField()
    date = StringField()
    detail = StringField()
    
class WorkInfo(EmbeddedDocument):
    name = StringField()
    date = StringField()
    location = StringField()
    position = StringField()
    detail = StringField()
    
class UserInfo(EmbeddedDocument):
    nickname = StringField()
    avatar = URLField()
    location = StringField()
    sex = BooleanField()
    birth = StringField()
    blog = URLField()
    site = URLField()
    intro = StringField()
    
    email = EmailField()
    qq = StringField()
    msn = StringField()
    
    n_follows = IntField()
    n_fans = IntField()
github iipeace / guider / agent / monitoring / models.py View on Github external
kernel = IntField(default=0)
    user = IntField(default=0)
    irq = IntField(default=0)
    nrCore = IntField(default=0)
    total = IntField(default=0)


class Memory(EmbeddedDocument):
    kernel = IntField(default=0)
    cache = IntField(default=0)
    free = IntField(default=0)
    anon = IntField(default=0)
    total = IntField(default=0)


class Storage(EmbeddedDocument):
    free = IntField(default=0)
    usage = IntField(default=0)
    total = IntField(default=0)


class Network(EmbeddedDocument):
    inbound = IntField(default=0)
    outbound = IntField(default=0)


class Datas(Document):
    timestamp = DateTimeField(default=datetime.utcnow)
    mac_addr = StringField()
    cpu = EmbeddedDocumentField(CPU)
    memory = EmbeddedDocumentField(Memory)
    storage = EmbeddedDocumentField(Storage)