Django Rest Framework model serializer: Set all fields to read only except one

Viewed 1813

The model that I'm using has a lot of fields. I want to be able to set all the fields to be read only except for one i.e. I want to allow only one particular field to be writable. Is there a shortcut to do this? I'm only aware of using "read_only_fields=('x','y') and I really don't want to type out all the fields especially if I'm going to make changes to the models later. "exclude =" also doesn't apply in this case.

1 Answers

Try to override serializer's __init__ method:

def __init__(self, *args, **kwargs):
    super(UserSerializer, self).__init__(*args, **kwargs)
    for field in self.fields:
        if field != 'some_required_filed':
            self.fields[field].read_only = True
Related