This commit is contained in:
Tom Christie 2014-10-08 16:43:33 +01:00
parent 14ae52a24e
commit 4c015df28c
2 changed files with 20 additions and 1 deletions

View File

@ -144,6 +144,24 @@ The corresponding code would now look like this:
logging.info('Creating ticket "%s"' % name)
serializer.save(user=request.user) # Include the user when saving.
#### Change to `validate_<field_name>`.
The `validate_<field_name>` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
def validate_score(self, attrs, source):
if attrs[score] % 10 != 0:
raise ValidationError('This field should be a multiple of ten.')
return attrs
This is now simplified slightly, and the method hooks simply take the value to be validated, and return it's validated value.
def validate_score(self, value):
if value % 10 != 0:
raise ValidationError('This field should be a multiple of ten.')
return value
Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.
#### Limitations of ModelSerializer validation.
This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes.

View File

@ -264,9 +264,10 @@ class ManyRelation(Field):
]
def to_representation(self, obj):
iterable = obj.all() if (hasattr(obj, 'all')) else obj
return [
self.child_relation.to_representation(value)
for value in obj.all()
for value in iterable
]
@property