Django-rest-framework: DRF 3.4.0 serializers.Meta.read_only_fields do not support '__all__'

Created on 18 Jul 2016  路  2Comments  路  Source: encode/django-rest-framework

like this:

class AssetStatusHistorySerializes(serializers.ModelSerializer):
    """"""
    class Meta:
        model = AssetStatusHistory
        exclude = ('asset', )
        read_only_fields = '__all__'

we will get this:

TypeError: The `read_only_fields` option must be a list or tuple. Got unicode.

Most helpful comment

Apologies for the necromancy on this issue, but I think there is a valid use case that this would help with. Say you have a model with fields 1...10. You want to allow user group A to be able to modify field 1 and allow user group B to be able to modify field 2, with any user able to read all fields.

The simplest way to do this would have something like

class Common(ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
        read_only_fields = '__all__'


class UserA(Common):
    one_field = CharField(read_only=False)


class UserB(Common):
    two_field = CharField(read_only=False)


def get_serializer_class(self):
    if self.request.user.is_a:
        return UserA
    elif self.request.user.is_b:
        return UserB
    else:
        return Common

All 2 comments

Documentation states read_only_fields should be a list or tuple.
If you don't want a writable entry point, you should tune the view not to accept creation/update.

Apologies for the necromancy on this issue, but I think there is a valid use case that this would help with. Say you have a model with fields 1...10. You want to allow user group A to be able to modify field 1 and allow user group B to be able to modify field 2, with any user able to read all fields.

The simplest way to do this would have something like

class Common(ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
        read_only_fields = '__all__'


class UserA(Common):
    one_field = CharField(read_only=False)


class UserB(Common):
    two_field = CharField(read_only=False)


def get_serializer_class(self):
    if self.request.user.is_a:
        return UserA
    elif self.request.user.is_b:
        return UserB
    else:
        return Common
Was this page helpful?
0 / 5 - 0 ratings