示例#1
0
    def bulk_create(self,
                    object_or_objects,
                    retrieve=False,
                    full_clean=False,
                    ordered=True):
        """Save Model instances in bulk.

        :parameters:
          - `object_or_objects`: A list of MongoModel instances or a single
            instance.
          - `retrieve`: Whether to return the saved MongoModel
            instances. If ``False`` (the default), only the ids will be
            returned.
          - `full_clean`: Whether to validate each object by calling
            the :meth:`~pymodm.MongoModel.full_clean` method before saving.
            This isn't done by default.
          - `ordered` (optional): If ``True`` (the default) documents will be
            inserted on the server serially, in the order provided. If an error
            occurs all remaining inserts are aborted. If ``False``, documents
            will be inserted on the server in arbitrary order, possibly in
            parallel, and all document inserts will be attempted.

        :returns: A list of ids for the documents saved, or of the
                  :class:`~pymodm.MongoModel` instances themselves if `retrieve`
                  is ``True``.

        example::

            >>> vacation_ids = Vacation.objects.bulk_create([
            ...     Vacation(destination='TOKYO', travel_method='PLANE'),
            ...     Vacation(destination='ALGIERS', travel_method='PLANE')])
            >>> print(vacation_ids)
            [ObjectId('578926716e32ab1d6a8dc718'),
             ObjectId('578926716e32ab1d6a8dc719')]

        """
        retrieve = validate_boolean('retrieve', retrieve)
        full_clean = validate_boolean('full_clean', full_clean)
        TopLevelMongoModel = _import('pymodm.base.models.TopLevelMongoModel')
        if isinstance(object_or_objects, TopLevelMongoModel):
            object_or_objects = [object_or_objects]
        object_or_objects = validate_list_or_tuple('object_or_objects',
                                                   object_or_objects)
        if full_clean:
            for object in object_or_objects:
                object.full_clean()
        docs = (obj.to_son() for obj in object_or_objects)
        ids = self._collection.insert_many(docs, ordered=ordered).inserted_ids
        if retrieve:
            return list(self.raw({'_id': {'$in': ids}}))
        return ids
示例#2
0
文件: fields.py 项目: paste/pymodm
    def __init__(self,
                 verbose_name=None,
                 mongo_name=None,
                 primary_key=False,
                 blank=False,
                 required=False,
                 default=None,
                 choices=None,
                 validators=None):
        """Create a new Field instance.

        :parameters:
          - `verbose_name`: A human-readable name for the Field.
          - `mongo_name`: The name of this field when stored in MongoDB.
          - `primary_key`: If ``True``, this Field will be used for the ``_id``
            field when stored in MongoDB. Note that the `mongo_name` of the
            primary key field cannot be changed from ``_id``.
          - `blank`: If ``True``, allow this field to have an empty value.
          - `required`: If ``True``, do not allow this field to be unspecified.
          - `default`: The default value to use for this field if no other value
            has been given.
          - `choices`: A list of possible values for the field. This can be a
            flat list, or a list of 2-tuples consisting of an allowed field
            value and a human-readable version of that value.
          - `validators`: A list of callables used to validate this Field's
            value.
        """
        self._verbose_name = validate_string_or_none('verbose_name',
                                                     verbose_name)
        self.mongo_name = validate_string_or_none('mongo_name', mongo_name)
        self.primary_key = validate_boolean('primary_key', primary_key)
        self.blank = validate_boolean('blank', blank)
        self.required = validate_boolean('required', required)
        self.choices = validate_list_tuple_or_none('choices', choices)
        self.validators = validate_list_tuple_or_none('validators', validators
                                                      or [])
        self.default = default
        # "attname" is the attribute name of this field on the Model.
        # We may be assigned a different name by the Model's metaclass later on.
        self.attname = mongo_name
        if self.primary_key and self.mongo_name not in (None, '_id'):
            raise ValueError('The mongo_name of a primary key must be "_id".')
        elif self.primary_key:
            self.mongo_name = '_id'
        self.__counter = MongoBaseField.__creation_counter
        MongoBaseField.__creation_counter += 1
示例#3
0
    def __init__(self, verbose_name=None, mongo_name=None, primary_key=False,
                 unique=False, blank=False, required=False,
                 default=None, choices=None, validators=None):
        """Create a new Field instance.

        :parameters:
          - `verbose_name`: A human-readable name for the Field.
          - `mongo_name`: The name of this field when stored in MongoDB.
          - `primary_key`: If ``True``, this Field will be used for the ``_id``
            field when stored in MongoDB. Note that the `mongo_name` of the
            primary key field cannot be changed from ``_id``.
          - `unique`: If ``True``, ensure that there is an index that enforces
            uniqueness on this Field's value.
          - `blank`: If ``True``, allow this field to have an empty value.
          - `required`: If ``True``, do not allow this field to be unspecified.
          - `default`: The default value to use for this field if no other value
            has been given.
          - `choices`: A list of possible values for the field. This can be a
            flat list, or a list of 2-tuples consisting of an allowed field
            value and a human-readable version of that value.
          - `validators`: A list of callables used to validate this Field's
            value.
        """
        self._verbose_name = validate_string_or_none(
            'verbose_name', verbose_name)
        self.mongo_name = validate_string_or_none('mongo_name', mongo_name)
        self.primary_key = validate_boolean('primary_key', primary_key)
        # "attname" is the attribute name of this field on the Model.
        # We may be assigned a different name by the Model's metaclass later on.
        self.unique = validate_boolean('unique', unique)
        self.blank = validate_boolean('blank', blank)
        self.required = validate_boolean('required', required)
        self.choices = validate_list_tuple_or_none('choices', choices)
        self.validators = validate_list_tuple_or_none(
            'validators', validators or [])
        self.default = default
        self.attname = mongo_name
        if self.primary_key and self.mongo_name not in (None, '_id'):
            raise ValueError(
                'The mongo_name of a primary key must be "_id".')
        elif self.primary_key:
            self.mongo_name = '_id'
        self.__counter = MongoBaseField.__creation_counter
        MongoBaseField.__creation_counter += 1
示例#4
0
    def bulk_create(self, object_or_objects, retrieve=False, full_clean=False):
        """Save Model instances in bulk.

        :parameters:
          - `object_or_objects`: A list of MongoModel instances or a single
            instance.
          - `retrieve`: Whether to return the saved MongoModel
            instances. If ``False`` (the default), only the ids will be
            returned.
          - `full_clean`: Whether to validate each object by calling
            the :meth:`~pymodm.MongoModel.full_clean` method before saving.
            This isn't done by default.

        :returns: A list of ids for the documents saved, or of the
                  :class:`~pymodm.MongoModel` instances themselves if `retrieve`
                  is ``True``.

        example::

            >>> vacation_ids = Vacation.objects.bulk_create([
            ...     Vacation(destination='TOKYO', travel_method='PLANE'),
            ...     Vacation(destination='ALGIERS', travel_method='PLANE')])
            >>> print(vacation_ids)
            [ObjectId('578926716e32ab1d6a8dc718'),
             ObjectId('578926716e32ab1d6a8dc719')]

        """
        retrieve = validate_boolean('retrieve', retrieve)
        full_clean = validate_boolean('full_clean', full_clean)
        TopLevelMongoModel = _import('pymodm.base.models.TopLevelMongoModel')
        if isinstance(object_or_objects, TopLevelMongoModel):
            object_or_objects = [object_or_objects]
        object_or_objects = validate_list_or_tuple(
            'object_or_objects', object_or_objects)
        if full_clean:
            for object in object_or_objects:
                object.full_clean()
        docs = (obj.to_son() for obj in object_or_objects)
        ids = self._collection.insert_many(docs).inserted_ids
        if retrieve:
            return list(self.raw({'_id': {'$in': ids}}))
        return ids
示例#5
0
    def save(self, cascade=None, full_clean=True, force_insert=False):
        """Save this document into MongoDB.

        If there is no value for the primary key on this Model instance, the
        instance will be inserted into MongoDB. Otherwise, the entire document
        will be replaced with this version (upserting if necessary).

        :parameters:
          - `cascade`: If ``True``, all dereferenced MongoModels contained in
            this Model instance will also be saved.
          - `full_clean`: If ``True``, the
            :meth:`~pymodm.MongoModel.full_clean` method
            will be called before persisting this object.
          - `force_insert`: If ``True``, always do an insert instead of a
            replace. In this case, `save` will raise
            :class:`~pymongo.errors.DuplicateKeyError` if a document already
            exists with the same primary key.

        :returns: This object, with the `pk` property filled in if it wasn't
                  already.

        """
        cascade = validate_boolean_or_none('cascade', cascade)
        full_clean = validate_boolean('full_clean', full_clean)
        force_insert = validate_boolean('force_insert', force_insert)
        if full_clean:
            self.full_clean()
        if cascade or (self._mongometa.cascade and cascade is not False):
            for field_name in self:
                for referenced_object in self._find_referenced_objects(
                        getattr(self, field_name)):
                    referenced_object.save()
        if force_insert or self._mongometa.pk.is_undefined(self):
            result = self._mongometa.collection.insert_one(self.to_son())
            self.pk = result.inserted_id
        else:
            result = self._mongometa.collection.replace_one(
                {'_id': self._mongometa.pk.to_mongo(self.pk)},
                self.to_son(),
                upsert=True)
        return self
示例#6
0
    def save(self, cascade=None, full_clean=True, force_insert=False):
        """Save this document into MongoDB.

        If there is no value for the primary key on this Model instance, the
        instance will be inserted into MongoDB. Otherwise, the entire document
        will be replaced with this version (upserting if necessary).

        :parameters:
          - `cascade`: If ``True``, all dereferenced MongoModels contained in
            this Model instance will also be saved.
          - `full_clean`: If ``True``, the
            :meth:`~pymodm.MongoModel.full_clean` method
            will be called before persisting this object.
          - `force_insert`: If ``True``, always do an insert instead of a
            replace. In this case, `save` will raise
            :class:`~pymongo.errors.DuplicateKeyError` if a document already
            exists with the same primary key.

        :returns: This object, with the `pk` property filled in if it wasn't
                  already.

        """
        cascade = validate_boolean_or_none('cascade', cascade)
        full_clean = validate_boolean('full_clean', full_clean)
        force_insert = validate_boolean('force_insert', force_insert)
        if full_clean:
            self.full_clean()
        if cascade or (self._mongometa.cascade and cascade is not False):
            for field_name in self:
                for referenced_object in self._find_referenced_objects(
                        getattr(self, field_name)):
                    referenced_object.save()
        if force_insert or self._mongometa.pk.is_undefined(self):
            result = self._mongometa.collection.insert_one(self.to_son())
            self.pk = result.inserted_id
        else:
            result = self._mongometa.collection.replace_one(
                {'_id': self._mongometa.pk.to_mongo(self.pk)},
                self.to_son(), upsert=True)
        return self