Пример #1
0
    def clean_fields(self, exclude=None):
        """Validate the values of all fields.

        This method will raise a :exc:`~pymodm.errors.ValidationError` that
        describes all issues with each field, if any field fails to pass
        validation.

        :parameters:
          - `exclude`: A list of fields to exclude from validation.

        """
        exclude = validate_list_tuple_or_none('exclude', exclude)
        exclude = set(exclude) if exclude else set()
        error_dict = {}
        for field in self._mongometa.get_fields():
            if field.attname in exclude:
                continue
            try:
                field_value = field.value_from_object(self)
                field_empty = field.is_undefined(self)
                if field_empty and field.required:
                    error_dict[field.attname] = [
                        ValidationError('field is required.')
                    ]
                elif not field_empty:
                    field.validate(field_value)
            except Exception as exc:
                error_dict[field.attname] = [ValidationError(exc)]
        if error_dict:
            raise ValidationError(error_dict)
Пример #2
0
    def clean_fields(self, exclude=None):
        """Validate the values of all fields.

        This method will raise a :exc:`~pymodm.errors.ValidationError` that
        describes all issues with each field, if any field fails to pass
        validation.

        :parameters:
          - `exclude`: A list of fields to exclude from validation.

        """
        exclude = validate_list_tuple_or_none('exclude', exclude)
        exclude = set(exclude) if exclude else set()
        error_dict = {}
        for field in self._mongometa.get_fields():
            if field.attname in exclude:
                continue
            try:
                field_value = field.value_from_object(self)
                field_empty = field.is_undefined(self)
                if field_empty and field.required:
                    error_dict[field.attname] = [ValidationError(
                        'field is required.')]
                elif not field_empty:
                    field.validate(field_value)
            except Exception as exc:
                error_dict[field.attname] = [ValidationError(exc)]
        if error_dict:
            raise ValidationError(error_dict)
Пример #3
0
    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
Пример #4
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
Пример #5
0
    def refresh_from_db(self, fields=None):
        """Reload this object from the database, overwriting local field values.

        :parameters:
          - `fields`: An iterable of fields to reload. Defaults to all fields.

        .. warning:: This method will reload the object from the database,
           possibly with only a subset of fields. Calling
           :meth:`~pymodm.MongoModel.save` after this may revert or unset
           fields in the database.

        """
        fields = validate_list_tuple_or_none('fields', fields)
        if self._qs is None:
            raise OperationError('Cannot refresh from db before saving.')
        qs = self._qs.values()
        if fields:
            qs = qs.only(*fields)
        db_inst = qs.first()

        self._set_attributes(db_inst)
        return self
Пример #6
0
    def refresh_from_db(self, fields=None):
        """Reload this object from the database, overwriting local field values.

        :parameters:
          - `fields`: An iterable of fields to reload. Defaults to all fields.

        .. warning:: This method will reload the object from the database,
           possibly with only a subset of fields. Calling
           :meth:`~pymodm.MongoModel.save` after this may revert or unset
           fields in the database.

        """
        fields = validate_list_tuple_or_none('fields', fields)
        if self._qs is None:
            raise OperationError('Cannot refresh from db before saving.')
        qs = self._qs.values()
        if fields:
            qs = qs.only(*fields)
        db_inst = qs.first()

        self._set_attributes(db_inst)
        return self