aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--docs/topics/3.0-announcement.md18
-rw-r--r--rest_framework/relations.py3
2 files changed, 20 insertions, 1 deletions
diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md
index 6520f2bd..26d261ed 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_<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.
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
index df5025b8..e9dd7dde 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