Skip to content

Instantly share code, notes, and snippets.

@aj07mm
Created June 25, 2020 16:21
Show Gist options
  • Save aj07mm/e83e76a8e80e7ebc12b0a32b08668f96 to your computer and use it in GitHub Desktop.
Save aj07mm/e83e76a8e80e7ebc12b0a32b08668f96 to your computer and use it in GitHub Desktop.
ReadWriteSerializerMethodField
class ReadWriteSerializerMethodField(serializers.Field):
def __init__(self, method_name=None, **kwargs):
self.method_name = method_name
kwargs['source'] = '*'
#kwargs['read_only'] = True
super(ReadWriteSerializerMethodField, self).__init__(**kwargs)
def bind(self, field_name, parent):
self.field_name = field_name
# In order to enforce a consistent style, we error if a redundant
# 'method_name' argument has been used. For example:
# my_field = serializer.SerializerMethodField(method_name='get_my_field')
default_method_name = 'get_{field_name}'.format(field_name=field_name)
assert self.method_name != default_method_name, (
"It is redundant to specify `%s` on SerializerMethodField '%s' in "
"serializer '%s', because it is the same as the default method name. "
"Remove the `method_name` argument." %
(self.method_name, field_name, parent.__class__.__name__)
)
# The method name should default to `get_{field_name}`.
if self.method_name is None:
self.method_name = default_method_name
super(ReadWriteSerializerMethodField, self).bind(field_name, parent)
def to_representation(self, value):
method = getattr(self.parent, self.method_name)
return method(value)
def to_internal_value(self, data):
return { self.field_name: data }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment