From 4c015df28cfb7dc7cf29f6dc4985c57e1f5cdc5d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 Oct 2014 16:43:33 +0100 Subject: [PATCH] Tweaks --- docs/topics/3.0-announcement.md | 18 ++++++++++++++++++ rest_framework/relations.py | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index 6520f2bdd..26d261edd 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -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_`. + +The `validate_` 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. diff --git a/rest_framework/relations.py b/rest_framework/relations.py index df5025b80..e9dd7ddea 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -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