niekas
niekas

Reputation: 9097

DRF ModelSerializer make all fields Read Only without specifying them explicitely

I was able to make read only model serializer, e.g.:

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = ['name', 'ratio']
        read_only_fields = fields

However, I tend to add/remove fields to/from Foo frequently. It would be much easier not to update my serializer each time Foo is modified. The fields = '__all__' is very handy:

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = '__all__'
        read_only_fields = fields

However, the read_only_fields does not accept __all__ as a valid option and raises this exception:

Exception Type: TypeError at /api/foo/
Exception Value: The `read_only_fields` option must be a list or tuple. Got str.

How could I mark all fields as read only without explicitely adding each field to read_only_fields list?

Upvotes: 5

Views: 2145

Answers (1)

zbusia
zbusia

Reputation: 601

You can extend get_fields method like this:

def get_fields(self):
    fields = super().get_fields()
    for field in fields.values():
        field.read_only = True
    return fields

Upvotes: 5

Related Questions