aboutsummaryrefslogtreecommitdiffstats
path: root/docs/api-guide/serializers.md
diff options
context:
space:
mode:
authorTom Christie2012-10-24 04:16:11 -0700
committerTom Christie2012-10-24 04:16:11 -0700
commit9a741e7ddb756eece1b7b2cca8620db052c57309 (patch)
treeb04c90dd1e15b09d76bf0ae83199bf62742b7231 /docs/api-guide/serializers.md
parent5d76f03ac6f4937aa4f52d43ddb8d014ff632780 (diff)
parent607c31c6d880501e5dc524fc5a5e1fc136b162fc (diff)
downloaddjango-rest-framework-9a741e7ddb756eece1b7b2cca8620db052c57309.tar.bz2
Merge pull request #318 from j4mie/field-validation
Implement per-field validation on Serializers
Diffstat (limited to 'docs/api-guide/serializers.md')
-rw-r--r--docs/api-guide/serializers.md23
1 files changed, 22 insertions, 1 deletions
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index c10a3f44..50505d30 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -76,7 +76,28 @@ Deserialization is similar. First we parse a stream into python native datatype
When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages.
-**TODO: Describe validation in more depth**
+### Field-level validation
+
+You can specify custom field-level validation by adding `validate_<fieldname>()` methods to your `Serializer` subclass. These are analagous to `clean_<fieldname>` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). Your `validate_<fieldname>` methods should either just return the attrs dictionary or raise a `ValidationError`. For example:
+
+ from rest_framework import serializers
+
+ class BlogPostSerializer(serializers.Serializer):
+ title = serializers.CharField(max_length=100)
+ content = serializers.CharField()
+
+ def validate_title(self, attrs, source):
+ """
+ Check that the blog post is about Django
+ """
+ value = attrs[source]
+ if "Django" not in value:
+ raise serializers.ValidationError("Blog post is not about Django")
+ return attrs
+
+### Final cross-field validation
+
+To do any other validation that requires access to multiple fields, add a method called `validate` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
## Dealing with nested objects