예제 #1
0
    def save(self):
        self.deserialize()
        if self.errors:
            raise ModelValidationError(self.errors)
        try:
            self.instance.clean_fields()
        except ValidationError as e:
            raise ModelValidationError(e.message_dict)
        self.instance.save()

        # Serialize related fields
        for key, val in self.data.items():
            if key not in self.related_fields:
                continue
            self._deserialize_related(key, val)

        # Serialize m2m fields
        for key, val in self.data.items():
            if key not in self.m2m_fields:
                continue
            self._deserialize_related(key, val, save_instance=True)
        return self.instance
예제 #2
0
    def deserialize(self):
        # Set initial data
        if not self._instance:
            self._instance = self.opts.model()

        for key, val in self.initial.items():
            setattr(self.instance, key, val)

        # Deserialize base fields
        for key, val in self.data.items():
            if key not in self.opts.update_fields or key not in self.base_fields:
                continue
            try:
                self.validate_field(key, val, self.data)
                self._deserialize_field(key, val)
            except ModelValidationError as err:
                self.errors.update(err.get_error_dict())

        if self.errors:
            raise ModelValidationError(errors=self.errors)

        return self.instance
 def validate_number(self, val):
     if val == 8:
         raise ModelValidationError({'number': ['number error']})
 def validate_text(self, val):
     if val == 'foo':
         raise ModelValidationError({'text': ['text error']})