Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
kbsol Avatar asked Sep 14 '18 08:09

kbsol


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
like image 129
neverwalkaloner Avatar answered Nov 13 '22 05:11

neverwalkaloner