diff options
| author | Jamie Matthews | 2012-10-24 09:28:10 +0100 |
|---|---|---|
| committer | Jamie Matthews | 2012-10-24 09:28:10 +0100 |
| commit | 51fae73f3d565e2702c72ff9841cc072d6490804 (patch) | |
| tree | 5353159bb62058ad3e8900428aa8aa738720b9b8 /docs/api-guide/serializers.md | |
| parent | 5d76f03ac6f4937aa4f52d43ddb8d014ff632780 (diff) | |
| download | django-rest-framework-51fae73f3d565e2702c72ff9841cc072d6490804.tar.bz2 | |
Implement per-field validation on Serializers
Diffstat (limited to 'docs/api-guide/serializers.md')
| -rw-r--r-- | docs/api-guide/serializers.md | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index c10a3f44..e1e12e74 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -78,6 +78,23 @@ When deserializing data, you always need to call `is_valid()` before attempting **TODO: Describe validation in more depth** +## Custom field validation + +Like Django forms, you can specify custom field-level validation by adding `clean_<fieldname>()` methods to your `Serializer` subclass. This method takes a dictionary of deserialized data as a first argument, and the field name in that data as a second argument (which will be either the name of the field or the value of the `source` argument, if one was provided.) It should either return the data dictionary or raise a `ValidationError`. For example: + + class BlogPostSerializer(Serializer): + title = serializers.CharField(max_length=100) + content = serializers.CharField() + + def clean_title(self, data, source): + """ + Check that the blog post is about Django + """ + value = data[source] + if "Django" not in value: + raise ValidationError("Blog post is not about Django") + return data + ## Dealing with nested objects The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, |
