I'm using Django Rest Framework and want to create a custom Field to use in my serializers.
class PivotField(serializers.Field):
def __init__(self, *args, **kwargs):
self.key_attr = kwargs.get('key_attr')
self.value_attr = kwargs.get('value_attr')
super(PivotField, self).__init__(*args, **kwargs)
def to_representation(self, value):
data = {}
for model in value.all():
# this is where I'd use the key_attr and value_attr
data[model.type.name] = model.uri
return data
I'd like to be able to pass additional arguments to the field like this.
resources = PivotField(key_attr='type.name', value_attr='uri')
However, I keep getting the following error.
TypeError: init() got an unexpected keyword argument 'key_attr'
Is there some way to register these as valid kwargs within the field?