def validate(self, obj, data, value, ctx=None): if ctx is None: ctx = {} errors = [] if isinstance(value, str): try: value = deserialize(value) except json.JSONDecodeError: raise exceptions.ValidationError( _('Does not appear to be valid json.')) if self.many and not isinstance(value, (list, tuple)): raise exceptions.ValidationError(_('Value must be a list.')) if not self.many: try: self.serializer.validate(obj=obj, data=value, ctx=ctx) except exceptions.ValidationError as exception: errors.append(exception.description) else: for item in value: try: self.serializer.validate(obj=obj, data=item, ctx=ctx) except exceptions.ValidationError as exception: errors.append(exception.description) if errors: raise exceptions.ValidationError(errors)
def test_serialize_uuid(self): d = uuid.UUID('abea9b06-43a1-4e84-ad75-fc0346a64497') data = { 'uuid': d, } res = json.deserialize(json.serialize(data)) self.assertEqual(res['uuid'], 'abea9b06-43a1-4e84-ad75-fc0346a64497')
def test_serialize_datetime(self): d = datetime.datetime(2016, 1, 1, 10, 32, 1) data = { 'date': d, } res = json.deserialize(json.serialize(data)) self.assertEqual(res['date'], '2016-01-01T10:32:01')
def validate_fields(self, obj, data, value, ctx=None): if isinstance(value, str): value = deserialize(value) if self.validator and value: if self.many: for item in value: self.validator.validate(obj=obj, data=item, ctx=ctx) else: self.validator.validate(obj=obj, data=value, ctx=ctx)
def to_python(self, obj, data, value, ctx=None): items = [] if isinstance(value, str): value = deserialize(value) if self.many: for item in value: items.append(self.serializer.save(obj=obj, data=item, ctx=ctx)) else: items.append(self.serializer.save(obj=obj, data=value, ctx=ctx)) return items if self.many else items[0]
def validate_structure(self, obj, data, value, ctx=None): if self.nullable and value is None: return value if isinstance(value, str): try: value = deserialize(value) except json.JSONDecodeError: raise exceptions.ValidationError( _('Does not appear to be valid json.')) if self.many and not isinstance(value, (list, tuple)): raise exceptions.ValidationError(_('Must be a list.'))
def to_python(self, obj, data, value, ctx=None): if isinstance(value, str): value = deserialize(value) items = [] if self.validator: if self.many: if value: for item in value: items.append(self.validator.validate(data=item)) else: items.append(self.validator.validate(data=value)) else: return value return items if self.many else items[0]
def to_data(self, obj, value, ctx=None): if isinstance(value, str): value = deserialize(value) return value