Move per-field and cross-field validation into a single method

This commit is contained in:
Jamie Matthews 2012-10-24 12:12:27 +01:00
parent d60d598e02
commit 607c31c6d8

View File

@ -208,33 +208,32 @@ class BaseSerializer(Field):
return reverted_data return reverted_data
def validate_fields(self, attrs): def perform_validation(self, attrs):
""" """
Run validate_<fieldname> methods on the serializer Run `validate_<fieldname>()` and `validate()` methods on the serializer
""" """
fields = self.get_fields(serialize=False, data=attrs, nested=self.opts.nested) fields = self.get_fields(serialize=False, data=attrs, nested=self.opts.nested)
for field_name, field in fields.items(): for field_name, field in fields.items():
try: try:
clean_method = getattr(self, 'validate_%s' % field_name, None) validate_method = getattr(self, 'validate_%s' % field_name, None)
if clean_method: if validate_method:
source = field.source or field_name source = field.source or field_name
attrs = clean_method(attrs, source) attrs = validate_method(attrs, source)
except ValidationError as err: except ValidationError as err:
self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages)
return attrs
def validate_all(self, attrs):
"""
Run the `validate` method on the serializer, if it exists
"""
try: try:
validate_method = getattr(self, 'validate', None) attrs = self.validate(attrs)
if validate_method:
attrs = validate_method(attrs)
except ValidationError as err: except ValidationError as err:
self._errors['non_field_errors'] = err.messages self._errors['non_field_errors'] = err.messages
return attrs
def validate(self, attrs):
"""
Stub method, to be overridden in Serializer subclasses
"""
return attrs return attrs
def restore_object(self, attrs, instance=None): def restore_object(self, attrs, instance=None):
@ -270,8 +269,7 @@ class BaseSerializer(Field):
self._errors = {} self._errors = {}
if data is not None: if data is not None:
attrs = self.restore_fields(data) attrs = self.restore_fields(data)
attrs = self.validate_fields(attrs) attrs = self.perform_validation(attrs)
attrs = self.validate_all(attrs)
else: else:
self._errors['non_field_errors'] = ['No input provided'] self._errors['non_field_errors'] = ['No input provided']