diff options
| author | Tom Christie | 2012-11-20 15:30:30 -0800 |
|---|---|---|
| committer | Tom Christie | 2012-11-20 15:30:30 -0800 |
| commit | 8e8b23b6a9aece32ae5c028a72969777f1ddc7ae (patch) | |
| tree | 786a0048b9ab07cee7dbabab6574cec1ced4781a /docs/api-guide | |
| parent | 3227a357cec2475b8295a67e9fd66f644ea5b0cd (diff) | |
| parent | 5f4c385a86b877217c1e1bc2eaff58206eabb747 (diff) | |
| download | django-rest-framework-8e8b23b6a9aece32ae5c028a72969777f1ddc7ae.tar.bz2 | |
Merge pull request #430 from j4mie/serializer-method-field
Serializer method field
Diffstat (limited to 'docs/api-guide')
| -rw-r--r-- | docs/api-guide/fields.md | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index d1c31ecc..914d0861 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -324,5 +324,25 @@ This field is always read-only. * `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`. * `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. +# Other Fields + +## SerializerMethodField + +This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: + + from rest_framework import serializers + from django.contrib.auth.models import User + from django.utils.timezone import now + + class UserSerializer(serializers.ModelSerializer): + + days_since_joined = serializers.SerializerMethodField('get_days_since_joined') + + class Meta: + model = User + + def get_days_since_joined(self, obj): + return (now() - obj.date_joined).days + [cite]: http://www.python.org/dev/peps/pep-0020/ [FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS |
