diff options
| author | Tom Christie | 2012-12-28 12:59:24 +0000 |
|---|---|---|
| committer | Tom Christie | 2012-12-28 12:59:24 +0000 |
| commit | 5d4ea3d23fdb173b4109a64b2d4231d93d394387 (patch) | |
| tree | a4baa31976e9b66528e4c0e7ca8cd604c2171232 /docs/api-guide/serializers.md | |
| parent | f7a82b6aeebaff2df78366a1e0b087c5afb2f459 (diff) | |
| download | django-rest-framework-5d4ea3d23fdb173b4109a64b2d4231d93d394387.tar.bz2 | |
Add .validate() example
Diffstat (limited to 'docs/api-guide/serializers.md')
| -rw-r--r-- | docs/api-guide/serializers.md | 17 |
1 files changed, 16 insertions, 1 deletions
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 19efde3c..da1efb8f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -110,7 +110,22 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio ### Object-level 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`. +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`. For example: + + from rest_framework import serializers + + class EventSerializer(serializers.Serializer): + description = serializers.CahrField(max_length=100) + start = serializers.DateTimeField() + finish = serializers.DateTimeField() + + def validate(self, attrs): + """ + Check that the start is before the stop. + """ + if attrs['start'] < attrs['finish']: + raise serializers.ValidationError("finish must occur after start") + return attrs ## Saving object state |
